﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Drawing.Printing;
using SpeechLib;
using System.Media;
using System.Timers;
using AllInOne.Entity;
using AllInOne.Utils;
using AllInOne.UsbCom;
using AllInOne.Pages;
using AllInOne.RdCard;
using System.Drawing;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ArcSoftFace.Utils;
using System.Configuration;
using System.IO;
using System.IO.Ports;
using AllInOne.Threading;
using AllInOne.PrintUtils;
using System.Printing;
using System.ComponentModel;
using Timer = System.Timers.Timer;
using System.Text.RegularExpressions;
using AllInOne.FeeUtils;
using AllInOne.MainPage;
using AllInOne.MainPages;
using AllInOne.HDI.CRT_591_M001;
using AllInOne.Classes;
using System.Windows.Media.Animation;
using AllInOne.Models;
using AllInOne.Common;
using Org.BouncyCastle.Utilities.Encoders;
using RestSharp;

namespace AllInOne
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // 国密规范正式私钥
        String prik = "00BC73D0B52B6856217FF7DD82008BCE6BD14FAD9339D2CC9F078AD9E6E72AFCCD";
        // 国密规范正式公钥  
        String pubk = "048700970482569577E8FD08AB5B177364670A4FB78265307533E40F10DFEE67C658DEBEAE1D2E9DC89D109EC42A1487A1A97338AD2A08C7B28F73155757ED890C";

        /// <summary>
        /// 当前识别到的人员信息 
        /// </summary>
        public DriverInfo DriverInfo { get; set; }

        /// <summary>
        /// 当前业务信息 
        /// </summary>
        public BusinessInfo businessInfo { get; set; }

        /// <summary>
        /// 当前入厂业务信息 
        /// </summary>
        public EnterBusinessInfo enterBusinessInfo { get; set; }


        /// <summary>
        /// 语音播报队列
        /// </summary>
        public readonly Queue<string> PlayVioceQueue = new Queue<string>();

        #region 自助机配置参数
        /// <summary>
        /// 自助机序列号
        /// </summary>
        public static string AllInOneSerialNumber = "";
        #endregion

        public static string GLBM = "";

        private static string IP_ADDRESS = "";

        private static string USER_NAME = "";
        private static string PASSWORD = "";
        public static string yxqz { get; set; }


        public bool loading { get; set; }



        public IdInfo idInfo { get; set; }

        public static bool PRINT_BACK_FLAG = false;

        public DrivingLicence drivingLicence { get; set; }

        public CarInfo carInfo { get; set; }

        public AppStep appStep = AppStep.INDEX;

        public App_Step app_Step = App_Step.INDEX;

        /// <summary>
        /// 当前人脸信息
        /// </oummary>
        public FaceInfo faceInfo { get; set; }

        /// <summary>
        /// 首页
        /// </summary>
        private IndexPage indexPage = null;

        /// <summary>
        /// 主首页
        /// </summary>
        private AllInOne.MainPages.IndexMainPage indexMainPage = null;


        private IndexDrivingLicencePage indexDrivingLicencePage = null;


        private IndexReturnPage indexReturnPage = null;

        private IndexCarPage indexCarPage = null;

        /// <summary>
        /// 表格页
        /// </summary>
        private TablePage tablePage = null;

        //private DemoPrintPage demoPrintPage = null;


        private ReadCardTipsPage readCardTipsPage = null;

        private ReadCardTips_Page readCardTips_Page = null;

        /// <summary>
        /// 签名页
        /// </summary>
        private SignPadPage signPadPage = null;

        /// <summary>
        ///  读取身份证页面
        /// </summary>
        private ReadCardPage readCardPage = null;

        /// <summary>
        ///  读取身份证页面
        /// </summary>
        private ReadCard_Page readCard_Page = null;


        private PhotoTipsPage photoTipsPage = null;

        private ChoosePhotoPage choosePhotoPage = null;

        private LicenseNumberInputPage licenseNumberInputPage = null;

        /// <summary>
        /// 驾驶证信息确认页面
        /// </summary>
        private ConfirmLicenceInfoPage confirmLicenceInfoPage = null;

        private ModifyPhonePage modifyPhonePage = null;

        private CarNumberInputPage carNumberInputPage = null;

        private VinInputPage vinInputPage = null;

        private ConfirmCarInfoPage confirmCarInfoPage = null;

        private VerifyCodeInputPage verifyCodeInputPage = null;

        #region 录入信息发卡
        private GiveCard_Page giveCard_Page = null;

        //车牌号输入
        private PlateInPut plateInPut = null;

        //备案号输入
        private PutOnRecordInPut putOnRecordInPut = null;

        //出厂信息录入界面
        private GiveCard_PageOut giveCard_PageOut = null;

        //厂内流转信息录入
        private GiveCard_PageInner giveCard_PageInner = null;

        //阴极铜制卡信息录入
        private GiveCard_PageOutYinJiTong giveCard_PageOutYinJiTong = null;
        #endregion

        /// <summary>
        /// 小票页面
        /// </summary>
        private TicketPage ticketPage = null;

        private SerialNumberInputPage serialNumberInputPage = null;

        private DemoRFCardPage demoRFCardPage = null;

        private PrintProcessPage printProcessPage = null;

        //打印控件
        private PrintDocument pd = new PrintDocument();

        //外部扫码枪
        private CommBar barCodeOuter = new CommBar();

        //IC卡读卡器
        private CommReadCard commReadCard = new CommReadCard();

        private CameraWindow cameraWindow = null;

        private SCMOutputWindow scmOutputWindow = new SCMOutputWindow();

        private int LNMJ_YEAR1;
        private int LNMJ_YEAR2;
        private int LNMJ_YEAR3;

        //程序当前状态
        public AppStep CURRENT_STEP = AppStep.INDEX;

        //空闲时间
        public int IDEL_TIME_LIMIT = 10;

        public int RESULT_IDEL_TIME_LIMIT = 10;

        public string PHOTO_PRINTER_NAME = "";
        public string LICENCE_PRINTER_NAME = "";

        //外部条形码扫码枪串口号
        public string BARCODE_PORTNAME;

        //空闲时间计时器
        private System.Timers.Timer idelTimeTimer;
        private Timer keyboardTimer;
        /// <summary>
        /// 空闲时间
        /// </summary>
        private int idelTime;

        /// <summary>
        /// 错误标志
        /// </summary>
        private bool errorFlag = false;
        /// <summary>
        /// 错误提示
        /// </summary>
        private string errorTips = "";

        /// <summary>
        /// 通信失败次数
        /// </summary>
        private int communicationFailedCount = 0;

        /// <summary>
        /// 上次通信检查时间
        /// </summary>
        private long lastCommunicationTime = 0;

        private Timer heartbeatTimer = new Timer();

        private byte[] lastCommand;


        private ConfirmPhotoPage confirmPhotoPage;


        #region 自助机相关信息
        //日期 2023年1月11日

        /// <summary>
        /// 用于验证服务器是不正常连接
        /// </summary>
        private Thread ThreadConnectServer = null;
        #endregion


        public void SetError(string tips)
        {
            this.errorFlag = true;
            this.errorTips = tips;
        }

        public MainWindow()
        {
            SimpleConsole.WriteInfo("自助终端系统启动", this);
            InitializeComponent();
        }

        public void InitKeyboradTimer() {
            this.keyboardTimer = new Timer();
            this.keyboardTimer.Interval = 500;
            this.keyboardTimer.Elapsed += new ElapsedEventHandler(delegate (object sender,ElapsedEventArgs e)
            {
                KeyBoardUtil.keybd_event(System.Windows.Forms.Keys.Enter, 0, 0, 0);
            });
        }

        public void StartInputEnter() {
            this.keyboardTimer.Enabled = true;
        }


        public void StopInputEnter()
        {
            this.keyboardTimer.Enabled = false;
        }


        /// <summary>
        /// 与服务器的连接心跳
        /// </summary>
        private void initHeartbeat()
        {
            this.heartbeatTimer.Interval = 1000;
            this.heartbeatTimer.Elapsed += new ElapsedEventHandler(delegate (object sender, ElapsedEventArgs e)
            {
                //1ticks=100纳秒=0.1微秒  1毫秒=10000tick 此处为60*5秒
                if (DateTime.Now.Ticks - lastCommunicationTime > 3000000000)
                {
                    if (this.scmStep == ScmStep.FREE)
                    {
                        this.checkCommunication();
                        this.lastCommunicationTime = DateTime.Now.Ticks;
                    }
                }
            });
            this.heartbeatTimer.Enabled = true;
        }

        private void checkServerCommunication()
        {
            this.communicationFailedCount = 0;
            this.SendMsgToScm(ComCommand.START_COMMUNICATION_CHECKING);
        }

        private void checkCommunication()
        {
            this.communicationFailedCount = 0;

            #region 与服务器连接
            //定义委托
            Action<string> message_show = delegate (string message)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString(message);
                }));
            };
            if (ServiceWebApi.CheckConnectServer(message_show))
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString("连接服务器成功！");
                }));
            }
            else
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString("连接服务器失败！");
                    SimpleConsole.WriteInfo($"连接服务器{ServiceWebApi.BASE_URL} 失败", this);
                }));
            }
            #endregion
        }

        /// <summary>
        /// 加载初始化信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //初始化配置参数
            this.InitProperties();
            InitWindow();


            #region 网络连接情况提示
            WindowToolTip.Opacity = 0;//不显示
            SetInformationString("正在连接服务器...");

            ThreadConnectServer = new Thread(ThreadCheckConnectServer);
            ThreadConnectServer.IsBackground = true;
            ThreadConnectServer.Start();
            #endregion

            //this.InitScm();
            //this.InitController();

            //-----------------------------------------------------------------------
            //初始化收发卡一体机通信
            if (SystemParam.TestSendCard == 0)
            {
                this.InitCRT591MR01();
            }

            //this.printProcessPage.InitPrintTask();

            //PrintDrivingLicence("1234455");
            //UsbPosPrintApi.printTicket("2191016126619");

            //DrivingLicence dl = ServiceApi.GetdrivingLicenseByIdNumber("370602198304112315");
            //MessageBox.Show(dl.xm);

            //this.PrintLnmj("1191010321366");
            //this.PreparePrintPhoto();

            //DemoPrintPage demoPrintPage = new DemoPrintPage();
            //demoPrintPage.initWindow();
            //demoPrintPage.InitPrintTask();
            //showPage(demoPrintPage);

            //this.businessInfo.lsh = "2191012111111";
            //this.businessInfo.businessType = BusinessType.QMHZ;

            //UsbPosPrintApi.printTicket("2191012111111");
            //this.ticketPage.InitPage();
            //this.SendMsgToController(new byte[] { 0xaa, 0xb3, 0x01, 0x01, 0x00, 0x00, 0x00, 0xdd });  //补正换证业务受理结束
            //this.showPage(this.ticketPage);
            //this.appStep = AppStep.TICKET_RESULT;

            //语音播报
            Thread ThreadPlayVioce = new Thread(PlayVioce);
            ThreadPlayVioce.IsBackground = true;
            ThreadPlayVioce.Start();
        }
        private void SetInformationString(string str)
        {
            if (WindowToolTip.Opacity == 1)
            {
                DoubleAnimation hidden = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(100));
                hidden.Completed += delegate
                {
                    DoubleAnimation show = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(100));
                    WindowToolTip.Text = str;
                    WindowToolTip.BeginAnimation(OpacityProperty, show);
                };
                WindowToolTip.BeginAnimation(OpacityProperty, hidden);
            }
            else
            {
                DoubleAnimation show = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(100));
                WindowToolTip.Text = str;
                WindowToolTip.BeginAnimation(OpacityProperty, show);
            }
        }

        /// <summary>
        /// 功能：用于验证服务器是不正常连接
        /// 日期：2023年1月11日
        /// </summary>
        private void ThreadCheckConnectServer()
        {
            //定义委托
            Action<string> message_show = delegate (string message)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString(message);
                }));
            };
            //通
            if (ServiceWebApi.CheckConnectServer(message_show))
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString("连接服务器成功！");
                }));
            }
            else
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    SetInformationString("连接服务器失败！");
                    SimpleConsole.WriteInfo($"连接服务器{ServiceWebApi.BASE_URL} 失败", this);
                }));
            }
        }



        public void InitProperties()
        {
            AppSettingsReader reader = new AppSettingsReader();
            IDEL_TIME_LIMIT = (int)reader.GetValue("IDEL_TIME_LIMIT", typeof(int));
            RESULT_IDEL_TIME_LIMIT = (int)reader.GetValue("RESULT_IDEL_TIME_LIMIT", typeof(int));
            BARCODE_PORTNAME = (string)reader.GetValue("BARCODE_PORTNAME", typeof(string));
            SCM_BAUDRATE = (int)reader.GetValue("SCM_BAUDRATE", typeof(int));
            CONTROLLER_PORTNAME = (string)reader.GetValue("CONTROLLER_PORTNAME", typeof(string));
            CONTROLLER_BAUDRATE = (int)reader.GetValue("CONTROLLER_BAUDRATE", typeof(int));
            SCM_PORTNAME = (string)reader.GetValue("SCM_PORTNAME", typeof(string));
            PHOTO_PRINTER_NAME = (string)reader.GetValue("PHOTO_PRINTER_NAME", typeof(string));
            LICENCE_PRINTER_NAME = (string)reader.GetValue("LICENCE_PRINTER_NAME", typeof(string));
            IP_ADDRESS = (string)reader.GetValue("IP_ADDR", typeof(string));
            USER_NAME = (string)reader.GetValue("USER_NAME", typeof(string));
            PASSWORD = (string)reader.GetValue("PASSWORD", typeof(string));
            LNMJ_YEAR1 = (int)reader.GetValue("LNMJ_YEAR1", typeof(int));
            LNMJ_YEAR2 = (int)reader.GetValue("LNMJ_YEAR2", typeof(int));
            LNMJ_YEAR3 = (int)reader.GetValue("LNMJ_YEAR3", typeof(int));

            GLBM = (string)reader.GetValue("GLBM", typeof(string));

            ChoosePhotoPage.HUE = (int)reader.GetValue("HUE", typeof(int));
            ChoosePhotoPage.BRIGHTNESS = (int)reader.GetValue("BRIGHTNESS", typeof(int));
            ChoosePhotoPage.SATURATION = (int)reader.GetValue("SATURATION", typeof(int));

            //CameraPage.LIGHT_NORMAL = (string)reader.GetValue("LIGHT_NORMAL", typeof(string));
            //CameraPage.LIGHT_PHOTO = (string)reader.GetValue("LIGHT_PHOTO", typeof(string));
            //CameraPage.PHOTO_CAMERA_NAME = (string)reader.GetValue("PHOTO_CAMERA_NAME", typeof(string));
            //CameraPage.RGB_CAMERA_NAME = (string)reader.GetValue("RGB_CAMERA_NAME", typeof(string));
            //CameraPage.IR_CAMERA_NAME = (string)reader.GetValue("IR_CAMERA_NAME", typeof(string));
            //CameraPage.CAMERA_MODE = (string)reader.GetValue("CAMERA_MODE", typeof(string));

            //CameraPage.MOVE_SPEED = (int)reader.GetValue("MOVE_SPEED", typeof(int));
            //CameraPage.CAMERA_ZOOM = (float)reader.GetValue("CAMERA_ZOOM", typeof(float));
            //CameraPage.PHOTO_ZOOM = (float)reader.GetValue("PHOTO_ZOOM", typeof(float));
            //CameraPage.FACE_VERIFY_THRESHOLD = (float)reader.GetValue("FACE_VERIFY_THRESHOLD", typeof(float));
            PRINT_BACK_FLAG = (bool)reader.GetValue("PRINT_BACK_FLAG", typeof(bool));
            //FeeUtil.FEE_URL = (string)reader.GetValue("FEE_URL", typeof(string));
            //FeeUtil.FEE_AREA_CODE = (string)reader.GetValue("FEE_AREA_CODE", typeof(string));
            //FeeUtil.FEE_USERNAME = (string)reader.GetValue("FEE_USERNAME", typeof(string));
            //FeeUtil.FEE_PASSWORD = (string)reader.GetValue("FEE_PASSWORD", typeof(string));
            //FeeUtil.FEE_ZTH = (string)reader.GetValue("FEE_ZTH", typeof(string));

            //参数读取
            AllInOneSerialNumber = (string)reader.GetValue("AllInOneSerialNumber", typeof(string));
        }

        public void InitWindow()
        {
            #region 自助机初始化
            this.Top = 0;
            this.Left = 0;
            this.Topmost = false;
            SimpleConsole.WriteInfo("程序启动", this);


            //初始化调用接口地址
            ServiceWebApi.InitProperties(SystemParam.ApiUrl);

            //还未测试--01--打印机相关
            InitPosPrinter();

            //页面01--三个按钮信息界面
            this.indexMainPage = new MainPages.IndexMainPage(this);

            //页面02--入厂制卡菜单页面
            this.indexDrivingLicencePage = new IndexDrivingLicencePage(this);

            //页面03--出厂还卡菜单页面
            this.indexReturnPage = new IndexReturnPage(this);

            //页面04--读取身份证信息页面实例化
            this.readCardTipsPage = new ReadCardTipsPage(this);

            #endregion

            ServiceApi.InitProperties();

            //InitIdelTimeTimer();

            //扫码设备先不要
            //this.InitBarcode();

            //this.faceInfo = new FaceInfo();

            //this.indexPage = new IndexPage(this);

            //this.indexCarPage = new IndexCarPage(this);

            this.signPadPage = new SignPadPage(this);

            this.tablePage = new TablePage(this);

            this.ticketPage = new TicketPage(this);

            this.confirmLicenceInfoPage = new ConfirmLicenceInfoPage(this);

            this.modifyPhonePage = new ModifyPhonePage(this);

            this.photoTipsPage = new PhotoTipsPage(this);

            this.choosePhotoPage = new ChoosePhotoPage(this);
            
            //读取身份证信息页面实例化
            this.readCardTips_Page = new ReadCardTips_Page(this);

            //输入车牌信息
            this.carNumberInputPage = new CarNumberInputPage(this);

            this.vinInputPage = new VinInputPage(this);

            this.confirmCarInfoPage = new ConfirmCarInfoPage(this);

            this.serialNumberInputPage = new SerialNumberInputPage(this);

            this.demoRFCardPage = new DemoRFCardPage(this);

            this.printProcessPage = new PrintProcessPage(this);

            this.confirmPhotoPage = new ConfirmPhotoPage(this);
            this.verifyCodeInputPage = new VerifyCodeInputPage(this);
            this.licenseNumberInputPage = new LicenseNumberInputPage(this);

            this.giveCard_Page = new GiveCard_Page(this);
            this.giveCard_PageOut = new GiveCard_PageOut(this);
            this.giveCard_PageInner = new GiveCard_PageInner(this);
            this.giveCard_PageOutYinJiTong = new GiveCard_PageOutYinJiTong(this);

            //输入车牌信息
            this.plateInPut = new PlateInPut(this);
            //输入备案号信息
            this.putOnRecordInPut = new PutOnRecordInPut(this);


            //SimpleConsole.WriteInfo("初始化视频采集设备", this);
            //InitCameraPage();

            //SimpleConsole.WriteInfo("初始化二代证读卡器", this);
            //InitReadCardPage();


            SimpleConsole.WriteInfo("初始化二代证读卡器", this);
            InitReadCard_Page();


            //InitCameraWindow();

            //------
            //初始化步骤提示窗口
            //InitTipStepWindow();

            //导航至首页
            ResetIndex();

            //连接服务器心跳
            this.initHeartbeat();
        }

        public void ShowConfirmPhotoPage(string zp, long zpId)
        {
            this.confirmPhotoPage.InitPage(zp, zpId);
            this.showPage(this.confirmPhotoPage);
        }
        /// <summary>
        /// 初始化读卡界面
        /// </summary>
        public void InitReadCardPage()
        {
            this.readCardPage = new ReadCardPage(this);
            SimpleConsole.WriteInfo("开始加载二代证读卡器", this);
            this.readCardPage.InitReader();
            SimpleConsole.WriteInfo("初始化读卡任务计时器", this);
            this.readCardPage.InitTimer();
        }

        /// <summary>
        /// 初始化二代证读卡器
        /// </summary>
        public void InitReadCard_Page()
        {
            this.readCard_Page = new ReadCard_Page(this);
            SimpleConsole.WriteInfo("开始加载二代证读卡器", this);
            this.readCard_Page.InitReader();
            SimpleConsole.WriteInfo("初始化读卡任务计时器", this);
            this.readCard_Page.InitTimer();
        }

        public void ShowJdcIndex()
        {
            this.showPage(this.indexCarPage);
        }

        public void ShowJszIndex()
        {
            //显示另外的页面：
            this.showPage(this.indexDrivingLicencePage);
        }

        /// <summary>
        /// 进入【制卡操作】页面功能展示 
        /// </summary>
        public void ShowZkczIndex()
        {
            this.showPage(this.indexDrivingLicencePage);
        }

        #region 出厂还卡
        /// <summary>
        /// 出厂可操作的页面功能展示 
        /// </summary>
        public void ShowReturnIndex()
        {
            //this.showPage(this.indexReturnPage);
            //2023年7月3日 以最新的页面处理，不用再选一次，而直接进行页面，进行还卡。

            try
            {
                CardModel authModel = ShowReadCard();
                if (authModel != null && !string.IsNullOrEmpty(authModel.CardNumber))
                {
                    BackICardByCardNum(authModel.CardNumber);
                }
                else
                {
                    MessageBox.Show("还卡失败,未读取到卡号,请取出你的卡片！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("还卡出错！");
                SimpleConsole.WriteInfo("出厂还卡错误" + ex.ToString(), this);
            }
        }


        /// <summary>
        /// 弹出刷卡窗体并返回值
        /// </summary>
        /// <returns></returns>
        private CardModel ShowReadCard()
        {
            ReadCard readCard = new ReadCard(Hdle);
            bool? result = readCard.ShowDialog();
            if (result == true)
            {
                return new CardModel() { AuthType = readCard.AuthType, CardNumber = readCard.AuthCode };
            }
            else
                return null;
        }


        /// <summary>
        /// 根据卡号归还IC卡
        /// </summary>
        /// <param name="ICCardNum">卡号</param>
        public void BackICardByCardNum(string ICCardNum)
        {
            try
            {
                string msg = "";
                SimpleConsole.WriteInfo("还卡操作卡号" + ICCardNum, this);

                string url = ServiceWebApi.BASE_URL + "SSMachine/BackICardByCardNum";
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                //request.AddHeader("Accept", "*/*");//‘可省略
                request.AddParameter("CardNum", ICCardNum);
                var response = client.Execute(request);
                if (!string.IsNullOrEmpty(response.Content))
                {
                    SimpleConsole.WriteOprateLog($"【{ICCardNum}】还卡返回信息" + response.Content, null);
                    BackInfo backInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<BackInfo>(response.Content);
                    if (backInfo.code == 200)//还卡，并将出门证打印出来
                    {
                        ExitViewModel exitViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ExitViewModel>(backInfo.data.ToString());
                        string IdentityNum = exitViewModel.IdentityNum;
                        if (!string.IsNullOrEmpty(IdentityNum) && IdentityNum.Length == 18)
                        {
                            if (SystemParam.HiddenBirthdy)//处理是否隐藏生日
                            {
                                if (IdentityNum.Length == 18)
                                {
                                    //7-14是生日位
                                    string tempStr = IdentityNum.Substring(0, 10) + "****" + IdentityNum.Substring(14, 4);
                                    IdentityNum = tempStr;
                                }
                            }
                        }

                        //并将卡传到收卡箱中 "移卡到盒里成功"
                        if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                        {
                            //软件中的打印
                            List<string> InfoList = new List<string>();
                            InfoList.Add("出门证");
                            InfoList.Add(exitViewModel.Plate);
                            InfoList.Add(exitViewModel.RegName);
                            InfoList.Add(IdentityNum);
                            InfoList.Add(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            try
                            {
                                Printer printer1 = new Printer
                                {
                                    LoginID = 12,
                                    InfoList = InfoList
                                };
                                //调用打印
                                //去掉打印
                                //printer1.Print();
                                LogHelper.WriteLog("打印出门证：完成！");
                            }
                            catch (Exception ex)
                            {
                                Log.Info($"打印出门证出错：" + ex.ToString());
                            }
                            //进卡口关闭
                            try
                            {
                                if (!GrantCardClient.NoCardIn(Hdle, "00", out msg))
                                {
                                    Log.Info($"进卡口关闭失败！");
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Info($"进卡口关闭出错：" + ex.ToString());
                            }
                            this.ShowText("还卡成功！");
                            this.PlayVioceQueue.Enqueue("还卡成功。");
                            return;
                        }
                        //还卡失败--将卡推送到最前面。
                        if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                        {
                            MessageBox.Show("还卡失败，请取走你的卡片!");
                            return;
                        }
                    }
                    else if (backInfo.code == 201)
                    {
                        //将错误信息组合起来传到前台
                        switch (backInfo.data.ToString())
                        {
                            case "1"://"未识别的卡,不能进行还卡"
                            case "3"://"此卡已经完成称重,可以还卡,收回到卡槽,但更新数据库卡注册信息失败";
                            case "4"://"此卡未完成称重,不能还卡,卡重新从卡槽吐出";
                                //做一个兼容：【已归还的卡,不能重复还卡】2023年4月20日
                                if (backInfo.message != null && backInfo.message == "已归还的卡,不能重复还卡")
                                {
                                    if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                                    {
                                        this.ShowText("还卡成功！");
                                        this.PlayVioceQueue.Enqueue("还卡成功。");
                                        this.ResetIndex();
                                        return;
                                    }
                                }
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    this.ShowText("还卡失败");
                                    this.PlayVioceQueue.Enqueue("还卡失败");
                                    MessageBox.Show($"还卡失败,{backInfo.message} 请取走你的卡片!");
                                }
                                break;
                            case "5"://此卡没有过车记录,直接还卡,不打印出门证
                            case "6"://卡信息是厂内流转货物,直接还卡,不打印出门证
                            case "9"://此卡没有过车记录,直接还卡,不打印出门证
                                if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg))
                                {
                                    this.ShowText("还卡成功！");
                                    this.PlayVioceQueue.Enqueue("还卡成功。");
                                    this.ResetIndex();
                                    return;
                                }
                                else
                                {
                                    //卡推送卡机失败，则吐出来
                                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                    {
                                        this.ShowText("还卡失败");
                                        this.PlayVioceQueue.Enqueue("还卡失败,移动回收盒失败");
                                    }
                                }
                                break;
                            //case "7"://此卡已经完成称重,可以还卡
                            //break;
                            case "8":
                                if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                                {
                                    this.ShowText("还卡失败");
                                    this.PlayVioceQueue.Enqueue(backInfo.message);
                                    return;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("连接服务器失败！");
                    //还卡失败--将卡推送到最前面。
                    if (GrantCardClient.MoveCardToFront1(Hdle, "00", out msg))
                    {
                        MessageBox.Show("还卡失败，请取走你的卡片!");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteError("还卡失败出错" + ex.ToString(), null);
            }
            this.ResetIndex();
        }

        #endregion


        /// <summary>
        /// 进入【制卡操作】页面功能展示 
        /// </summary>
        public void ShowTestPage()
        {
            this.showPage(this.demoRFCardPage);
        }
        /// <summary>
        /// 初始化空闲时间计时器
        /// </summary>
        public void InitIdelTimeTimer()
        {

            this.idelTimeTimer = new System.Timers.Timer();
            this.idelTimeTimer.Interval = 1000;
            this.idelTimeTimer.Enabled = true;
            this.idelTimeTimer.Elapsed += new ElapsedEventHandler(delegate (object sender, ElapsedEventArgs e) {
                this.idelTime++;

                if (this.idelTime > IDEL_TIME_LIMIT)
                {
                    if (this.appStep != AppStep.INDEX)
                    {
                        this.ResetIndex();
                    }
                    else
                    {
                        //this.cameraPage.StartVerifyGender();
                    }
                }

                if (this.appStep == AppStep.TICKET_RESULT)
                {
                    if (this.idelTime > RESULT_IDEL_TIME_LIMIT)
                    {
                        this.ResetIndex();
                    }
                }
            });
        }

        public void ResetIdelTime()
        {
            this.idelTime = 0;
        }

        /// <summary>
        /// 导航至首页
        /// </summary>
        public void ResetIndex()
        {
            if (loading)
            {
                return;
            }

            this.appStep = AppStep.INDEX;
            this.scmStep = ScmStep.FREE;
            this.businessInfo = new BusinessInfo();
            this.drivingLicence = new DrivingLicence();
            this.idInfo = null;
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.grdMask.Visibility = Visibility.Hidden;
                this.grdAlert.Visibility = Visibility.Hidden;
                this.grdConfirm.Visibility = Visibility.Hidden;
                //this.showPage(this.indexPage);
                this.showPage(this.indexMainPage);
            }));
            //this.cameraPage.StartVerifyGender();
            //this.cameraPage.StopPhotoThread();
            //this.cameraPage.StopPhoto();

            //this.readCardPage.StopRead();

            this.SendMsgToScm(ComCommand.CAMERA_SELF_CHECKING_START);
            this.SendMsgToController(new byte[] { 0xaa, 0xb3, 0x01, 0x01, 0x00, 0x00, 0x00, 0xdd }); //返回首页通知单片机
            this.inputCarLicenseNumberFlag = false;
            this.CloseBarcode();
            this.ShowText("");
            //返回首页--修改相应的硬件通信状态
        }


        /// <summary>
        /// 人脸性别验证失败次数
        /// </summary>
        private int genderVerifyFaildCount = 0;

        /// <summary>
        /// 设置人脸性别 
        /// </summary>
        /// <param name="gender"></param>
        public void setFaceGender(int gender)
        {
            if (this.faceInfo == null)
            {
                this.faceInfo = new FaceInfo();

            }

            if (gender > -1)
            {
                this.faceInfo.gender = gender;
                //this.cameraPage.StopVerifyGender();
                this.genderVerifyFaildCount = 0;
                if (this.appStep == AppStep.INDEX)
                {
                    long time1 = DateTime.Now.Ticks;
                    this.PlaySound(Properties.Resources.male_welcome, Properties.Resources.female_welcome);

                    long time2 = DateTime.Now.Ticks;
                    Console.WriteLine("播放声音时间:{0}", (time2 - time1) / 10000);
                }

                return;
            }
            else
            {
                this.genderVerifyFaildCount++;
            }
            if (this.genderVerifyFaildCount >= 50)
            {
                this.faceInfo.gender = 0;
                //this.cameraPage.StopVerifyGender();
                this.genderVerifyFaildCount = 0;
                if (this.appStep == AppStep.INDEX)
                {
                    long time1 = DateTime.Now.Ticks;
                    this.PlaySound(Properties.Resources.male_welcome, Properties.Resources.female_welcome);

                    long time2 = DateTime.Now.Ticks;
                    Console.WriteLine("播放声音时间:{0}", (time2 - time1) / 10000);
                }
            }
        }


        public void SetSignInfo(string qm, long qmId)
        {
            this.businessInfo.qmtp = qm;
            this.businessInfo.qmId = qmId;
            this.tablePage.InitPage();
            this.showPage(this.tablePage);
        }

        /// <summary>
        /// 选择业务类型
        /// </summary>
        /// <param name="businessType"></param>
        public void ChooseBusiness(BusinessType businessType)
        {
            if (PrinterUtil.GetPrinterStat(PHOTO_PRINTER_NAME)!=PrinterStatus.FREE || PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME)!=PrinterStatus.FREE)
            {
                this.Alert("提示", "打印机存在未完成任务，请联系管理员处理。");
                return;
            }

            string cardtype = "";


            this.businessInfo = new BusinessInfo();
            this.businessInfo.businessType = businessType;
            switch (businessType)
            {
                case BusinessType.RCZK:
                case BusinessType.CCZK:
                case BusinessType.CNLZZK:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadIC_Card(cardtype);
                    break;
                case BusinessType.QMHZ:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadIC_Card(cardtype);
                    break;
                case BusinessType.CCSL:
                //case BusinessType.QMHZ:
                case BusinessType.SHHZ:
                case BusinessType.YSBZ:
                case BusinessType.LNMJ:
                    //this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    //this.StartReadCard();
                    break;
                case BusinessType.ZJDY://与手动发卡--改成二次发卡也行
                    this.appStep = AppStep.INPUT_SERIAL_NUMBER;
                    this.serialNumberInputPage.InitPage();
                    this.showPage(serialNumberInputPage);
                    break;
                case BusinessType.ZZPZ:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadCard();
                    break;
                case BusinessType.ShouDongFaKa:
                    this.appStep = AppStep.INPUT_SERIAL_NUMBER;
                    this.serialNumberInputPage.InitPage();
                    this.showPage(serialNumberInputPage);
                    break;

                case BusinessType.CeShiFaKaJi://测试发卡机
                    this.appStep = AppStep.INPUT_SERIAL_NUMBER;
                    this.demoRFCardPage.InitPage();
                    this.showPage(demoRFCardPage);
                    break;
            }

        }

        /// <summary>
        /// 选择入厂业务类型 设置业务类型--为了调试改变业务类型参数而改动的
        /// </summary>
        /// <param name="businessType"></param>
        public void Choose_Business(EnterBusinessType enterBusinessType)
        {
            //是否还有未出的卡信息，或者打印磅单信息
            //if (PrinterUtil.GetPrinterStat(PHOTO_PRINTER_NAME) != PrinterStatus.FREE || PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME) != PrinterStatus.FREE)
            //{
            //    this.Alert("提示", "打印机存在未完成任务，请联系管理员处理。");
            //    return;
            //}
            string cardtype = "";
            switch (enterBusinessType)
            {
                case EnterBusinessType.RCZK:
                    cardtype = "RCZK";
                    break;                
                case EnterBusinessType.CCZK:
                    cardtype = "CCZK";
                    break;
                case EnterBusinessType.CNLZZK:
                    cardtype = "CNLZZK";
                    break;
                case EnterBusinessType.YJTZK:
                    cardtype = "YJTZK";
                    break;
                case EnterBusinessType.CCHK:
                    cardtype = "CCHK";
                    break;
                case EnterBusinessType.RCSMXXLR:
                    cardtype = "RCSMXXLR";//入厂货物--扫码制卡
                    break;
            }

            this.enterBusinessInfo = new EnterBusinessInfo();
            this.enterBusinessInfo.enterBusinessType = enterBusinessType;
            switch (enterBusinessType)
            {
                //制卡操作--身份识别
                case EnterBusinessType.RCZK:
                case EnterBusinessType.CCZK:
                case EnterBusinessType.CNLZZK:
                case EnterBusinessType.YJTZK:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadIC_Card(cardtype);
                    //此处将入口记录下来
                    break;
                case EnterBusinessType.RCSMXXLR://入厂货物-扫码制卡
                    this.StartRead_QR_Code();
                    break;
                //制卡操作--信息录入
                case EnterBusinessType.XXLR:
                    this.app_Step = App_Step.GIVE_INFOR_STEP11;
                    this.giveCard_Page.InitPage();
                    this.showPage(giveCard_Page);
                    break;
                case EnterBusinessType.CCXXLR://出厂-信息录入
                    this.app_Step = App_Step.GIVE_INFOR_STEP11;
                    this.giveCard_PageOut.InitPage();
                    this.showPage(giveCard_PageOut);
                    break;
                case EnterBusinessType.CNLZXXLR://厂内流转-信息录入
                    this.app_Step = App_Step.GIVE_INFOR_STEP11;
                    this.giveCard_PageInner.InitPage();
                    this.showPage(giveCard_PageInner);
                    break;
                case EnterBusinessType.YJTXXLR://阴极铜制卡-信息录入
                    this.app_Step = App_Step.GIVE_INFOR_STEP11;
                    this.giveCard_PageOutYinJiTong.InitPage();
                    this.showPage(giveCard_PageOutYinJiTong);
                    break;
                //出厂还卡
                case EnterBusinessType.CCHK:
                    this.ShowReturnIndex();
                    break;
                //数据查询
                case EnterBusinessType.SBSFZ:
                    this.app_Step = App_Step.IDENTITY_VERIFY_STEP0;
                    this.StartReadID_Card();
                    break;
                case EnterBusinessType.LRXXZK:
                    this.app_Step = App_Step.GIVE_INFOR_STEP11;
                    this.giveCard_Page.InitPage();
                    this.showPage(giveCard_Page);
                    break;
                case EnterBusinessType.CXKXX:
                    this.app_Step = App_Step.INPUT_SERIAL_NUMBER;
                    this.serialNumberInputPage.InitPage();
                    this.showPage(serialNumberInputPage);
                    break;
                case EnterBusinessType.CeShiFaKaJi://测试发卡机
                    this.appStep = AppStep.INPUT_SERIAL_NUMBER;
                    this.demoRFCardPage.InitPage();
                    this.showPage(demoRFCardPage);
                    break;
            }

        }
        /// <summary>
        /// 选择出厂业务类型
        /// </summary>
        /// <param name="businessType"></param>
        public void ChooseOutBusiness(BusinessType businessType)
        {
            if (PrinterUtil.GetPrinterStat(PHOTO_PRINTER_NAME) != PrinterStatus.FREE || PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME) != PrinterStatus.FREE)
            {
                this.Alert("提示", "打印机存在未完成任务，请联系管理员处理。");
                return;
            }
            string cardtype = "";
            this.businessInfo = new BusinessInfo();
            this.businessInfo.businessType = businessType;
            switch (businessType)
            {
                case BusinessType.ZKCZ:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadIC_Card(cardtype);
                    break;

                case BusinessType.QMHZ:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadIC_Card(cardtype);
                    break;
                case BusinessType.CCSL:
                //case BusinessType.QMHZ:
                case BusinessType.SHHZ:
                case BusinessType.YSBZ:
                case BusinessType.LNMJ:
                    //this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    //this.StartReadCard();
                    break;
                case BusinessType.ZJDY:
                    this.appStep = AppStep.INPUT_SERIAL_NUMBER;
                    this.serialNumberInputPage.InitPage();
                    this.showPage(serialNumberInputPage);
                    break;
                case BusinessType.ZZPZ:
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP0;
                    this.StartReadCard();
                    break;
            }
        }
        /// <summary>
        /// 开始读取身份证卡信息
        /// </summary>
        public void StartReadID_Card()
        {
            MessageBox.Show("进入了读取身份证信息页面！");
            string cardtype = "";
            this.readCard_Page.InitPage();
            this.readCardTips_Page.InitPage(cardtype);
            this.showPage(this.readCardTips_Page);
            this.readCardTips_Page.StartTimer();

            //---test 先禁用StartRead()
            this.readCard_Page.StartRead();
        }

        /// <summary>
        /// 显示文本的线程代理
        /// </summary>
        /// <param name="text">string</param>
        private delegate void ShowTextHandle(string text);

        /// <summary>
        /// 向底部展示提示信息
        /// </summary>
        /// <param name="text">string</param>
        public void ShowText(string text)
        {
            string MsgType = "操作成功"; 
            string tip_Title = "入厂发卡";
            string tip_Content = "卡槽无卡";
            tip_Content = text;

            //switch (MsgType)
            //{
            //    case "操作成功":
            //        Tip_Content.Background = System.Windows.Media.Brushes.DarkGreen;
            //        break;
            //    case "操作失败":
            //        Tip_Content.Background = System.Windows.Media.Brushes.Red;
            //        break;
            //    case "提示":
            //        Tip_Content.Background = System.Windows.Media.Brushes.Black;
            //        break;
            //}
            if (this.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
            {
                this.Dispatcher.Invoke(new ShowTextHandle(this.ShowText), text);
            }
            else
            {
                //this.Tip_Title.Text = "【" + tip_Title + "】";
                this.Tip_Content.Text = tip_Content;
            }
        }

        /// <summary>
        /// 向底部展示提示信息
        /// </summary>
        /// <param name="text">string</param>
        public void ShowTipText(string MsgType, string tip_Title, string tip_Content)
        {
            //switch (MsgType)
            //{
            //    case "操作成功":
            //        Tip_Content.Background = System.Windows.Media.Brushes.DarkGreen;
            //        break;
            //    case "操作失败":
            //        Tip_Content.Background = System.Windows.Media.Brushes.Red;
            //        break;
            //    case "提示":
            //        Tip_Content.Background = System.Windows.Media.Brushes.Black;
            //        break;
            //}
            if (this.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
            {
                this.Dispatcher.Invoke(new ShowTextHandle(this.ShowText), tip_Content);
            }
            else
            {
                //this.Tip_Title.Text = "【" + tip_Title + "】";
                this.Tip_Content.Text = tip_Content;
            }
        }

        /// <summary>
        /// 制卡方式：出厂制卡，入厂制卡，厂内流转
        /// </summary>
        public void StartReadIC_Card(string cardtype)
        {
            this.ShowText("读取身份证信息");
            //给一个弹出框，然后传递数据

            this.readCard_Page.InitPage();
            this.readCardTips_Page.InitPage(cardtype);
            this.showPage(this.readCardTips_Page);
            this.readCardTips_Page.StartTimer();
            this.readCard_Page.StartRead();
        }




        /// <summary>
        /// 开始
        /// </summary>
        public void StartReadCard()
        {
            this.readCardPage.InitPage();
            this.readCardTipsPage.InitPage();
            this.showPage(this.readCardTipsPage);
            this.readCardTipsPage.StartTimer();
            this.readCardPage.StartRead();
        }
        public void SetFaceVerifyResult(bool result, string xczp)
        {
            this.businessInfo.xczp = xczp;
            this.readCardPage.SetFaceVerifyResult(result);

            if (result)
            {
                switch (this.businessInfo.businessType)
                {
                    case BusinessType.QMHZ:
                    case BusinessType.YSBZ:
                    case BusinessType.SHHZ:
                        var thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate ()
                        {
                            this.ShowLoading();
                            this.drivingLicence = ServiceApi.GetdrivingLicenseByIdNumber(this.idInfo.getId());
                            //this.drivingLicence = null;
                            //this.drivingLicence = new DrivingLicence();
                            if (this.drivingLicence != null)
                            {
                                string xm = this.idInfo.getName().Replace("\0", "").Replace(" ", "");
                                string sfzmhm = this.idInfo.getId().Replace("\0", "").Replace(" ", "");
                                Thread.Sleep(2000);
                                this.appStep = AppStep.IDENTITY_VERIFY_STEP3;
                                this.Dispatcher.Invoke(new Action(delegate ()
                                {
                                    this.confirmLicenceInfoPage.InitPage();
                                    this.showPage(this.confirmLicenceInfoPage);
                                }));
                            }
                            else
                            {
                                this.appStep = AppStep.IDENTITY_VERIFY_STEP4;
                                this.Alert("错误", "  未查询到您的驾照信息。", new OkDelegate(delegate ()
                                {
                                    this.ResetIndex();
                                }));
                            }
                            this.HideLoading();
                        }))
                        { IsBackground = true };
                        thread.Start();
                        break;
                    case BusinessType.LNMJ:
                        new System.Threading.Thread(new System.Threading.ThreadStart(delegate ()
                        {
                            Thread.Sleep(2000);
                            this.Dispatcher.Invoke(new Action(delegate ()
                            {
                                this.carNumberInputPage.InitPage();
                                this.showPage(this.carNumberInputPage);
                            }));
                        }))
                        { IsBackground = true }.Start();
                        break;
                    case BusinessType.ZJDY:


                        JObject zpJson = ServiceApi.hqzp(this.businessInfo.sfzmhm);
                        string zpResult = zpJson["result"].ToString();
                        if (zpResult == "ok")
                        {
                            string zp = zpJson["tp"].ToString();
                            Bitmap zpBitmap = ImageUtil.StringToBitmap(zp);
                            zpBitmap.Save("license_photo.png");
                        }
                        else
                        {

                        }



                        //this.printProcessPage.ResetProcess();
                        //this.PrintDrivingLicence(this.businessInfo.lsh);
                        this.ShowVerifyCode(this.businessInfo.lsh);
                        break;
                    case BusinessType.ZZPZ:
                        this.StartTakePhoto();
                        break;
                }
            }
            else
            {
                this.appStep = AppStep.IDENTITY_VERIFY_STEP4;
                this.Confirm("提示", "人脸比对未通过，请平视镜头重新验证。", "重新验证", "返回首页", new YesDelegate(delegate ()
                {
                    //this.cameraPage.StartVerify();
                }), new NoDelegate(delegate () {
                    this.ResetIndex();
                }));

            }
        }


        private bool inputCarLicenseNumberFlag = false;

        public void SetCarNumber(string carNumber)
        {
            this.businessInfo.hphm = carNumber;


            this.vinInputPage.InitPage();
            this.showPage(this.vinInputPage);


            //this.showPage(this.licenseNumberInputPage);
            //this.inputCarLicenseNumberFlag = true;
            //this.OpenBarcode();
            //this.PlaySound(Properties.Resources.male_scan_car_license_number, Properties.Resources.female_scan_car_license_number);


        }


        public void SetCarLicenseNumber(string carLicenseNumber) {
            if (carLicenseNumber.Length>13)
            {
                carLicenseNumber = carLicenseNumber.Substring(0, 13);
            }
            this.CloseBarcode();
            this.ShowLoading();

            this.carInfo = ServiceApi.GetCarInfo(this.businessInfo.hphm);
            this.HideLoading();



            string message = "";


            if (carInfo != null && carInfo.xszbh != null && carInfo.xszbh.Length > 6)
            {

                SimpleConsole.WriteInfo(string.Format("inputNumber:{0},xszbh:{1},",carLicenseNumber,carInfo.xszbh), this);
                if (carLicenseNumber == carInfo.xszbh) 
                {


                    int dayId = DateTime.Now.Year * 10000 + DateTime.Now.Month * 100 + DateTime.Now.Day;
                    int monthId = DateTime.Now.Year * 12 + DateTime.Now.Month;


                    if (carInfo.yxqz != null && carInfo.yxqz.Length >= 10)
                    {
                        int yxqz = int.Parse(carInfo.yxqz.Substring(0, 4)) * 12 + int.Parse(carInfo.yxqz.Substring(5, 2));
                        SimpleConsole.WriteInfo(string.Format("monthId:{0},yxqz:{1}", monthId, yxqz), this);
                        if (yxqz - monthId > 2)
                        {
                            this.Alert("提示", "车辆审核有效期为：" + carInfo.yxqz + ",当前无法办理自助审车业务。如有疑问请咨询工作人员。", delegate () {
                                this.ResetIndex();
                            });
                            return;
                        }

                    }

                    if (carInfo.bxzzrq != null && carInfo.bxzzrq.Length >= 10)
                    {
                        int bxzzrq = int.Parse(carInfo.bxzzrq.Substring(0, 10).Replace("-", ""));
                        SimpleConsole.WriteInfo(string.Format("dayId:{0},bxzzrq:{1}", dayId, bxzzrq), this);

                        if (bxzzrq < dayId)
                        {
                            this.Alert("提示", "电子保险单保险终止日期为：" + carInfo.bxzzrq + ",无法办理自助审车业务。如有疑问请咨询工作人员。"
                                , delegate () {
                                    this.ResetIndex();
                                });
                            return;
                        }
                    }
                    else
                    {
                        this.Alert("提示", "未查询到电子保险单信息,无法办理自助审车业务。如有疑问请咨询工作人员。", delegate () {
                            this.ResetIndex();
                        });
                        return;

                    }






                    int lnmjIndex = 0;
                    SimpleConsole.WriteInfo(this.carInfo.yxqz, this);
                    int lnmjYear = Int32.Parse(this.carInfo.yxqz.Substring(0, 4)) + 2;
                    SimpleConsole.WriteInfo(lnmjYear + "," + LNMJ_YEAR1, this);

                    if (lnmjYear == LNMJ_YEAR1)
                    {
                        lnmjIndex = 1;
                    }

                    if (lnmjYear == LNMJ_YEAR2)
                    {
                        lnmjIndex = 2;
                    }

                    if (lnmjYear == LNMJ_YEAR3)
                    {
                        lnmjIndex = 3;
                    }
                    if (lnmjIndex == 0)
                    {
                        this.Alert("提示", "本机中缺少打印六年免检所需年份(" + lnmjYear + "年)的标签", delegate ()
                        {
                            this.ResetIndex();
                        });
                        return;
                    }
                    else
                    {
                        this.businessInfo.lnmjIndex = lnmjIndex;
                    }





                    if (carInfo.lsh != null && carInfo.lsh.Length > 10)
                    {
                        this.businessInfo.lsh = carInfo.lsh;
                        this.Dispatcher.Invoke(new Action(delegate ()
                        {
                            this.ShowVerifyCode(carInfo.lsh);
                        }));
                        return;
                    }


                    this.Dispatcher.Invoke(new Action(delegate ()
                    {
                        this.confirmCarInfoPage.InitPage();
                        this.showPage(this.confirmCarInfoPage);
                    }));
                    return;
                }
                else
                {
                    message = "行驶证条码不正确。";
                }
            }
            else
            {
                message = "未查询到您输入车牌号码对应的车辆。";
            }
            this.Confirm("提示", message, "重新输入", "取消办理",
            new YesDelegate(delegate ()
            {
                this.BackToInputCarNumber();
            }),
            new NoDelegate(delegate ()
            {
                this.ResetIndex();
            })); ;
        }

        public void SetVinCode(string vinCode)
        {
            this.businessInfo.vin6 = vinCode;

            this.ShowLoading();

            this.carInfo = ServiceApi.GetCarInfo(this.businessInfo.hphm);
            this.HideLoading();



            string message = "";
            

            if (carInfo != null && carInfo.clsbdh != null && carInfo.clsbdh.Length>6)
            {


                var clsbdh = this.carInfo.clsbdh;
                clsbdh = clsbdh.Substring(clsbdh.Length - 6);
                Regex rex = new Regex("\\D");
                clsbdh = rex.Replace(clsbdh, "0");
                if (clsbdh == vinCode)
                {


                    int dayId = DateTime.Now.Year * 10000 + DateTime.Now.Month * 100 + DateTime.Now.Day;
                    int monthId = DateTime.Now.Year * 12 + DateTime.Now.Month;


                    if (carInfo.yxqz != null && carInfo.yxqz.Length >= 10)
                    {
                        int yxqz = int.Parse(carInfo.yxqz.Substring(0, 4)) * 12 + int.Parse(carInfo.yxqz.Substring(5, 2));
                        SimpleConsole.WriteInfo(string.Format("monthId:{0},yxqz:{1}", monthId, yxqz), this);
                        if (yxqz - monthId > 2)
                        {
                            this.Alert("提示", "车辆审核有效期为：" + carInfo.yxqz + ",当前无法办理自助审车业务。如有疑问请咨询工作人员。", delegate () {
                                this.ResetIndex();
                            });
                            return;
                        }

                    }

                    if (carInfo.bxzzrq != null && carInfo.bxzzrq.Length >= 10)
                    {
                        int bxzzrq = int.Parse(carInfo.bxzzrq.Substring(0,10).Replace("-", ""));
                        SimpleConsole.WriteInfo(string.Format("dayId:{0},bxzzrq:{1}", dayId, bxzzrq), this);

                        if (bxzzrq < dayId)
                        {
                            this.Alert("提示", "电子保险单保险终止日期为：" + carInfo.bxzzrq + ",无法办理自助审车业务。如有疑问请咨询工作人员。"
                                , delegate () {
                                    this.ResetIndex();
                                });
                            return;
                        }
                    }
                    else
                    {
                        this.Alert("提示", "未查询到电子保险单信息,无法办理自助审车业务。如有疑问请咨询工作人员。", delegate () {
                            this.ResetIndex();
                        });
                        return;

                    }


                    



                    int lnmjIndex = 0;
                    SimpleConsole.WriteInfo(this.carInfo.yxqz, this);
                    int lnmjYear = Int32.Parse(this.carInfo.yxqz.Substring(0, 4)) + 2;
                    SimpleConsole.WriteInfo(lnmjYear+","+LNMJ_YEAR1, this);

                    if (lnmjYear == LNMJ_YEAR1)
                    {
                        lnmjIndex = 1;
                    }

                    if (lnmjYear == LNMJ_YEAR2)
                    {
                        lnmjIndex = 2;
                    }

                    if (lnmjYear == LNMJ_YEAR3)
                    {
                        lnmjIndex = 3;
                    }
                    if (lnmjIndex == 0)
                    {
                        this.Alert("提示", "本机中缺少打印六年免检所需年份("+lnmjYear+"年)的标签", delegate ()
                        {
                            this.ResetIndex();
                        });
                        return;
                    }
                    else
                    {
                        this.businessInfo.lnmjIndex = lnmjIndex;
                    }

                    



                    if (carInfo.lsh != null && carInfo.lsh.Length>10)
                    {
                        this.businessInfo.lsh = carInfo.lsh;
                        this.ShowVerifyCode(carInfo.lsh);
                        return;
                    }

                    this.confirmCarInfoPage.InitPage();
                    this.showPage(this.confirmCarInfoPage);
                    return;
                }
                else
                {
                    message = "您输入的车辆识别代号后6位不正确。";
                }
            }
            else
            {
                message = "未查询到您输入车牌号码对应的车辆。";
            }
            this.Confirm("提示", message, "重新输入", "取消办理",
            new YesDelegate(delegate ()
            {
                this.BackToInputCarNumber();
            }),
            new NoDelegate(delegate ()
            {
                this.ResetIndex();
            }));

            
        }


        public void SetSerialNumber(string lsh)
        {
            this.ShowLoading();
            this.businessInfo.lsh = lsh;

            //string msg;
            //JObject lsxx = ServiceWebApi.QuerySerialNumber(lsh,out msg);

            JObject lsxx = ServiceWebApi.QuerySerialNumber(lsh);
            string result = (string)lsxx["Value3"];
            if (result == "有信息")
            {
                string sfzmhm = (string)lsxx["Value4"];
                if (sfzmhm == "可以发卡")
                {
                    this.businessInfo.sfzmhm = sfzmhm;
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP50;
                    this.StartReadCard();
                }
                else
                {
                    this.Alert("提示", "业务未到制证环节，请咨询工作人员。");
                }
            }
            else
            {
                this.Alert("提示", "未查询到流水信息，如有疑问请咨询工作人员。");
                SimpleConsole.WriteError("未查询到流水信息", this);
            }
            this.HideLoading();
        }
        
        /// <summary>
        /// 上面方法的备份
        /// </summary>
        /// <param name="lsh"></param>
        public void SetSerialNumber_Temp(string lsh)
        {
            this.CloseBarcode();
            this.ShowLoading();
            this.businessInfo.lsh = lsh;
            JObject lsxx = ServiceApi.cxlsxx(lsh);
            //string result = (string)lsxx["result"];
            string result = "结果";
            if (result != null && result == "ok")
            {
                string sfzmhm = (string)lsxx["sfzmhm"];
                string ywlx = (string)lsxx["ywlx"];
                string ywyy = (string)lsxx["ywyy"];
                string ffbz = (string)lsxx["ffbz"];
                if (ywlx == "C")
                {
                    this.businessInfo.sfzmhm = sfzmhm;
                    this.appStep = AppStep.IDENTITY_VERIFY_STEP50;
                    this.StartReadCard();
                }
                else
                {
                    this.Alert("提示", "业务未到制证环节，请咨询工作人员。");
                }
            }
            else
            {
                this.Alert("提示", "未查询到流水信息，如有疑问请咨询工作人员。");
                SimpleConsole.WriteError("未查询到流水信息", this);
            }
            this.HideLoading();
        }


        public void BackToInputCarNumber()
        {
            this.carNumberInputPage.InitPage();
            this.showPage(this.carNumberInputPage);
        }

        //同步摄像头图片
        public void SetVideoFrame(Bitmap newFrame)
        {
            if (this.appStep == AppStep.IDENTITY_VERIFY_STEP2)
            {
                this.Dispatcher.Invoke(new Action(delegate ()
                {
                    this.readCardPage.setPhoto(newFrame);
                }));
            }
        }

        public void StartTakePhoto()
        {
            //if (this.cameraPage.StartPhoto())
            //{
            //    this.photoTipsPage.InitPage();
            //    this.showPage(this.photoTipsPage);
            //}

        }



        public void SavePhoto(Bitmap photo)
        {
            new Thread(new ThreadStart(delegate ()
            {
                string zp = ImageUtil.BitmapToString(photo);
                long zpId = ServiceApi.UploadTp(this.idInfo.getId(), this.idInfo.getName(), zp, "zp");
                this.businessInfo.zp = zp;
                this.businessInfo.zpId = zpId;
            }))
            { IsBackground = true }.Start();
            if (this.businessInfo.businessType == BusinessType.ZZPZ)
            {
                this.Alert("提示", "拍照完成",delegate() {
                    this.ResetIndex();
                });

                new Thread(new ThreadStart(delegate ()
                {
                    Thread.Sleep(5000);
                    this.Dispatcher.Invoke(new Action(delegate ()
                    {
                        this.ResetIndex();
                    }));
                }))
                { IsBackground = true }.Start();

            }
            else {
                this.ShowSignPad();
            }
        }

        public void ConfirmZpId(long zpId)
        {
            this.businessInfo.zpId = zpId;
            this.ShowSignPad();
        }



        public void ShowChoosePhotoPage()
        {
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.choosePhotoPage.InitPage();
                this.showPage(this.choosePhotoPage);
            }));
        }

        public void AddPhotoToBeChoosed(Bitmap photo)
        {
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.choosePhotoPage.AddPhoto(photo);
            }));
        }


        public void ShowSignPad()
        {
            this.signPadPage.InitPage();
            this.showPage(this.signPadPage);
            //this.cameraPage.StopCamera();
        }

        public void ShowModifyPhone()
        {
            this.modifyPhonePage.InitPage();
            this.showPage(this.modifyPhonePage);
        }
        public void ModifyPhone(string sjhm)
        {
            this.businessInfo.sjhm = sjhm;
            this.confirmLicenceInfoPage.SetSjhm(sjhm);
            this.showPage(this.confirmLicenceInfoPage);
        }

        public void CancelModifyPhone()
        {
            this.showPage(this.confirmLicenceInfoPage);
        }


        #region 车牌输入

        /// <summary>
        /// 车牌手动输入--进入页面
        /// </summary>
        public void ShowPlateInPut()
        {
            this.plateInPut.InitPage();
            this.showPage(this.plateInPut);
        }

        /// <summary>
        /// 车牌手动输入--确定页面--即返回信息录入页面
        /// </summary>
        /// <param name=""></param>
        public void GiveCard_Page(string Plate)
        {
            this.businessInfo.strPlate = Plate;
            this.giveCard_Page.SetPlate(Plate);
            this.showPage(this.giveCard_Page);
        }
        #endregion

        #region 备案号输入

        /// <summary>
        /// 备案号手动输入--进入页面
        /// </summary>
        public void ShowPutOnRecordInPut(string strYNumber)
        {
            this.putOnRecordInPut.InitPage(strYNumber);
            this.showPage(this.putOnRecordInPut);
        }
        /// <summary>
        /// 备案号手动输入--确定页面--即返回信息录入页面
        /// </summary>
        /// <param name=""></param>
        public void GiveCard_Page_R(string YNumber)
        {
            switch (this.readCardTips_Page.cardtype)//卡类型
            {
                case "RCZK":
                    this.businessInfo.strYNumber = YNumber;
                    this.giveCard_Page.SetYNumber(YNumber);
                    this.showPage(this.giveCard_Page);
                    break;
                case "CCZK":
                    this.businessInfo.strYNumber = YNumber;
                    this.giveCard_PageOut.SetYNumber(YNumber);
                    this.showPage(this.giveCard_PageOut);
                    break;
                case "CNLZZK":
                    this.businessInfo.strYNumber = YNumber;
                    this.giveCard_Page.SetYNumber(YNumber);
                    this.showPage(this.giveCard_Page);
                    break;
            }
        }
        #endregion




        public void PrintTicket() {
            UsbPosPrintApi.printTicket(this.businessInfo.lsh);
            this.SendMsgToController(new byte[] { 0xaa, 0xb3, 0x01, 0x01, 0x00, 0x00, 0x00, 0xdd });  //补正换证业务受理结束
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.ticketPage.InitPage();
                this.showPage(this.ticketPage);
                this.appStep = AppStep.TICKET_RESULT;
            }));
        }


        


        public void SubmitBzhz()
        {
            JObject bzhzResult = ServiceApi.bzhz(this.businessInfo, this.drivingLicence);

            string result = (string)bzhzResult["result"];
            if (result == "ok")
            {
                string lsh = (string)bzhzResult["lsh"];
                SimpleConsole.WriteInfo("流水号:"+lsh,this);

                this.businessInfo.lsh = lsh;


                this.PrintTicket();

            }
            else
            {
                string msg = (string)bzhzResult["msg"];
                this.tablePage.HideTable();
                this.Alert("提示", string.Format("办理失败原因:“{0}”,请重试或联系管理员。", msg), delegate ()
                {
                    this.tablePage.ShowTable();
                    this.ResetIndex();
                });
                //string lsh = "2191012111111";
                //this.businessInfo.lsh = lsh;


                //UsbPosPrintApi.printTicket(lsh);
                //this.ticketPage.InitPage();
                //this.SendMsgToController(new byte[] { 0xaa, 0xb3, 0x01, 0x01, 0x00, 0x00, 0x00, 0xdd });  //补正换证业务受理结束
                //this.showPage(this.ticketPage);
                //this.appStep = AppStep.TICKET_RESULT;
            }
        }

        public void SubmitLnmj()
        {
            JObject lnmjResult = ServiceApi.lnmj(this.businessInfo, this.carInfo, GLBM);
            string result = (string)lnmjResult["result"];
            if (result == "ok")
            {
                string lsh = (string)lnmjResult["lsh"];
                this.businessInfo.lsh = lsh;
                SimpleConsole.WriteInfo("六年免检流水号" + lsh, this);
                
                this.ShowVerifyCode(this.businessInfo.lsh);

            }
            else
            {
                string msg = (string)lnmjResult["msg"];
                this.tablePage.HideTable();
                if (msg.IndexOf("终止日期")>-1)
                {
                    msg = "电子保险单已过有效期。";
                }


                this.Alert("提示", string.Format("办理失败原因:“{0}”,请重试或联系管理员。", msg), delegate () {
                    this.tablePage.ShowTable();
                    this.ResetIndex();
                });
            }
        }




        /// <summary>
        /// 初始化摄像头屏幕
        /// </summary>
        public void InitCameraWindow()
        {
            this.cameraWindow = new CameraWindow();
            this.cameraWindow.Show();
            this.cameraWindow.Top = 0;
            this.cameraWindow.Left = 1280;
            //this.cameraWindow.Topmost = true;
            //this.cameraWindow.showPage(cameraPage);
        }


        private void showPage(Page newPage)
        {
            this.navigating = true;
            this.canvasFrame.Content = newPage;
        }

        private void PrintPhoto()
        {
            PrinterUtil.SetDefaultPrinter(PHOTO_PRINTER_NAME);
            SimpleConsole.WriteInfo("打印任务开始", this);

            pd.PrintPage += this.printPhoto;

            pd.Print();
            SimpleConsole.WriteInfo("打印任务结束", this);
            Thread.Sleep(100);
            int i = 0;
            while (i<20)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(PHOTO_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    break;
                }
                Thread.Sleep(100);
                i++;
            }
            pd.PrintPage -= this.printPhoto;
        }

        private void PreparePrintPhoto() {
            PrinterUtil.SetDefaultPrinter(PHOTO_PRINTER_NAME);
            SimpleConsole.WriteInfo("打印任务开始", this);

            pd.PrintPage += this.printPhoto;
            
            pd.Print();
            SimpleConsole.WriteInfo("打印任务结束", this);

        }

        private void CheckPrintPhoto() {
            int i = 0;
            while (i<20)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(PHOTO_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    break;
                }
                Thread.Sleep(100);
                i++;
            }
            
            pd.PrintPage -= this.printPhoto;
        }


        public void printPhoto(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(System.Drawing.Image.FromFile("license_photo.png"), 245, 101, 83, 120);

        }


        public void printFront(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(System.Drawing.Image.FromFile(@"C:\\licence_front.png"), 0, 0, 340, 445);

        }

        public void printVoid(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(System.Drawing.Image.FromFile(@"C:\\void.png"), 0, 0, 260, 220);

        }

        public void printLnmj(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(System.Drawing.Image.FromFile(@"C:\\lnmj.png"), 0, 0, 200, 200);

        }
        /// <summary>
        /// 修改：2023年2月1日17:16:52，将private 改为 public 方便调试
        /// </summary>
        public void demoPrintLicenceFront()
        {
            LICENCE_PRINTER_NAME = "HPC01803970BEF(HP Laser MFP 131 133 135-138)";

            PrinterUtil.SetDefaultPrinter(LICENCE_PRINTER_NAME);
            pd.PrintPage += this.printFront;
            pd.Print();
            Thread.Sleep(100);
            while (true)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    Thread.Sleep(100);
                    break;
                }
                Thread.Sleep(100);
            }
            pd.PrintPage -= this.printFront;


        }

        private void PrintLicenceBack()
        {
            PrinterUtil.SetDefaultPrinter(LICENCE_PRINTER_NAME);

            Thread.Sleep(100);
            int i = 0;
            while (i < 50) 
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    Thread.Sleep(100);
                    break;
                }
                Thread.Sleep(100);
                i++;
            }


        }


        private void PrintVoidLogo()
        {
            PrinterUtil.SetDefaultPrinter(LICENCE_PRINTER_NAME);
            pd.PrintPage += this.printVoid;
            pd.Print();
            Thread.Sleep(2000);
            while (true)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    Thread.Sleep(100);
                    break;
                }
                Thread.Sleep(100);
            }
            pd.PrintPage -= this.printVoid;


        }



        private bool PrintLicenceFront(string zxbh, string lsh)
        {
            PrinterUtil.SetDefaultPrinter(LICENCE_PRINTER_NAME);
            this.StartInputEnter();

            bool printFlag = this.printProcessPage.StartPrintDrivingLicense(zxbh, lsh);
            Thread.Sleep(3000);

            for (int i = 0; i < 25; i++)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    Thread.Sleep(100);
                    break;
                }
                Thread.Sleep(100);
            }
            Thread.Sleep(500);
            this.StopInputEnter();
            return printFlag;


        }



        private bool StartPrintLnmj(string lsh)
        {
            PrinterUtil.SetDefaultPrinter(LICENCE_PRINTER_NAME);
            this.StartInputEnter();
            bool printFlag = this.printProcessPage.StartPrintLnmj(lsh);

            if (!printFlag)
            {
                return false;
            }
            Thread.Sleep(100);
            for (int i=0;i<25;i++)
            {
                PrinterStatus printerStatus = PrinterUtil.GetPrinterStat(LICENCE_PRINTER_NAME);
                if (printerStatus == PrinterStatus.FREE)
                {
                    break;
                }
                Thread.Sleep(200);
                
            }
            Thread.Sleep(500);

            this.StopInputEnter();
            return true;

        }







        public bool barcodeInitFlag = false;

        /// <summary>
        /// 初始化外部条形码扫描枪
        /// </summary>
        public void InitBarcode()
        {
            barCodeOuter.SerialPortValue(BARCODE_PORTNAME, 9600);
            try
            {
                if (barCodeOuter.Open())
                {

                    barCodeOuter.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(
                        delegate (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                        {

                            System.Threading.Thread.Sleep(100);
                            byte[] m_recvBytes = new byte[barCodeOuter.serialPort.BytesToRead];//定义缓冲区大小
                            int result = barCodeOuter.serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);//从串口读取数据
                            if (result <= 0)
                                return;
                            barCodeOuter.Code = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length);//对数据进行转换

                            //MessageBox.Show(">>"+barCodeOuter.Code+"<<");

                            if (inputCarLicenseNumberFlag)
                            {
                                this.SetCarLicenseNumber(barCodeOuter.Code);
                            }
                            else {
                                this.SetOuterBarCode(barCodeOuter.Code);

                            }

                            barCodeOuter.serialPort.DiscardInBuffer();
                        }
                    );
                    barcodeInitFlag = true;
                }
                else
                {
                    barcodeInitFlag = false;
                    MessageBox.Show("连接扫码设备失败。");

                }
            }
            catch (Exception e)
            {
                barcodeInitFlag = false;
                MessageBox.Show("连接扫码设备失败。");

            }
        }

        /// <summary>
        /// 初始化IC卡读卡器
        /// </summary>
        public void InitReadCard()
        {
            commReadCard.SerialPortValue(BARCODE_PORTNAME, 9600);
            try
            {
                if (commReadCard.Open())
                {

                    commReadCard.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(
                        delegate (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
                        {

                            System.Threading.Thread.Sleep(100);
                            byte[] m_recvBytes = new byte[commReadCard.serialPort.BytesToRead];//定义缓冲区大小
                            int result = commReadCard.serialPort.Read(m_recvBytes, 0, m_recvBytes.Length);//从串口读取数据
                            if (result <= 0)
                                return;
                            commReadCard.Code = Encoding.ASCII.GetString(m_recvBytes, 0, m_recvBytes.Length);//对数据进行转换

                            if (inputCarLicenseNumberFlag)
                            {
                                this.SetCarLicenseNumber(commReadCard.Code);
                            }
                            else
                            {
                                this.SetOuterBarCode(commReadCard.Code);

                            }

                            commReadCard.serialPort.DiscardInBuffer();
                        }
                    );
                    barcodeInitFlag = true;
                }
                else
                {
                    barcodeInitFlag = false;
                    MessageBox.Show("连接IC卡读卡器设备失败。");

                }
            }
            catch (Exception e)
            {
                barcodeInitFlag = false;
                MessageBox.Show("连接IC卡读卡器设备失败。");

            }
        }


        public void OpenBarcode()
        {
            if (barcodeInitFlag)
            {
                barCodeOuter.serialPort.Write(new byte[] { 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xF8 }, 0, 16);
            }
        }
        public void CloseBarcode()
        {
            if (barcodeInitFlag)
            {
                barCodeOuter.serialPort.Write(new byte[] { 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xF9 }, 0, 16);
            }
        }



        public void SetOuterBarCode(string code)
        {
            code = code.Replace("\r", "");
            if (this.appStep == AppStep.INPUT_SERIAL_NUMBER)
            {

                this.Dispatcher.Invoke(new Action(delegate ()
                {
                    this.serialNumberInputPage.SetSerialNumber(code);

                }));

                new Thread(new ThreadStart(delegate ()
                {
                    Thread.Sleep(1000);
                    this.Dispatcher.Invoke(new Action(delegate ()
                    {
                        this.SetSerialNumber(code);
                    }));
                }))
                { IsBackground = true }.Start();

            }
        }



        private SoundPlayer soundPlayer = null;

        public void PlaySound(System.IO.UnmanagedMemoryStream maleSound, System.IO.UnmanagedMemoryStream femaleSound)
        {
            if (soundPlayer != null)
            {
                soundPlayer.Stop();
            }
            if (this.faceInfo!=null && this.faceInfo.gender == 1)
            {

                soundPlayer = new SoundPlayer(femaleSound);
            }
            else
            {
                soundPlayer = new SoundPlayer(maleSound);
            }
            soundPlayer.Play();
        }




        public delegate void OkDelegate();
        OkDelegate okDelegate;

        public delegate void YesDelegate();
        YesDelegate yesDelegate;

        public delegate void NoDelegate();
        NoDelegate noDelegate;

        private int dialogWidth = 670;
        private int dialogHeight = 472;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="okDelegate"></param>
        public void Alert(string title, string content, OkDelegate okDelegate)
        {
            Alert(title, content, "确 定", okDelegate);
        }


        public void Alert(string title, string content, string btnOkText, OkDelegate okDelegate)
        {
            this.okDelegate = okDelegate;
            var dept = 0.01;

            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.txtAlertTitle.Text = title;
                this.txtAlertContent.Text = content;


                this.vbAlert.Height = dialogHeight * dept;
                this.vbAlert.Width = dialogWidth * dept;

                this.txtOk.Text = btnOkText;

                this.grdMask.Visibility = Visibility.Visible;
                this.grdAlert.Visibility = Visibility.Visible;
            }));

            var thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate ()
            {

                for (int i = 2; i <= 100; i++)
                {
                    Thread.Sleep(1);
                    this.Dispatcher.Invoke(new Action(delegate ()
                    {
                        this.vbAlert.Height = dialogHeight * dept * i;
                        this.vbAlert.Width = dialogWidth * dept * i;
                    }));
                }

            }))
            { IsBackground = true };
            thread.Start();
        }

        public void Alert(string title, string content)
        {
            this.Alert(title, content, null);
        }

        public void Confirm(string title, string content)
        {
            this.Confirm(title, content, null, null);
        }


        public void Confirm(string title, string content, YesDelegate yesDelegate, NoDelegate noDelegate)
        {
            Confirm(title, content, "确 定", "取 消", yesDelegate, noDelegate);
        }

        public void Confirm(string title, string content, string btnYesText, string btnNoText, YesDelegate yesDelegate, NoDelegate noDelegate)
        {
            this.yesDelegate = yesDelegate;
            this.noDelegate = noDelegate;
            var dept = 0.02;

            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.txtConfirmTitle.Text = title;
                this.txtConfirmContent.Text = content;
                this.vbConfirm.Height = dialogHeight * dept;
                this.vbConfirm.Width = dialogWidth * dept;

                this.txtYes.Text = btnYesText;
                this.txtNo.Text = btnNoText;

                this.grdMask.Visibility = Visibility.Visible;
                this.grdConfirm.Visibility = Visibility.Visible;
            }));
            var thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate ()
            {
                for (int i = 2; i <= 50; i++)
                {
                    Thread.Sleep(2);
                    this.Dispatcher.Invoke(new Action(delegate ()
                    {
                        this.vbConfirm.Height = dialogHeight * dept * i;
                        this.vbConfirm.Width = dialogWidth * dept * i;
                    }));
                }
            }))
            { IsBackground = true };
            thread.Start();
        }


        private void BtnOk_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.grdMask.Visibility = Visibility.Hidden;
            this.grdAlert.Visibility = Visibility.Hidden;
            if (okDelegate != null)
            {
                okDelegate();
            }
        }


        private void BtnYes_MouseUp(object sender, MouseButtonEventArgs e)
        {

            this.grdMask.Visibility = Visibility.Hidden;
            this.grdConfirm.Visibility = Visibility.Hidden;
            if (yesDelegate != null)
            {
                yesDelegate();
            }
        }

        private void BtnNo_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.grdMask.Visibility = Visibility.Hidden;
            this.grdConfirm.Visibility = Visibility.Hidden;
            if (noDelegate != null)
            {
                noDelegate();
            }
        }

        private void InitPosPrinter()
        {
            SimpleConsole.WriteInfo("打印机初始化", this);
            UsbPosPrintApi.InitProperties();
            //UsbPosPrintApi.printTicket("2191105123456");
        }


        private SerialPort scmPort = null;
        public string SCM_PORTNAME;
        public int SCM_BAUDRATE;





        /// <summary>
        /// 初始化单片机通信
        /// </summary>
        private void InitScm()
        {

            this.scmPort = new SerialPort();
            scmPort.BaudRate = SCM_BAUDRATE;
            scmPort.PortName = SCM_PORTNAME;

            try
            {
                scmPort.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("连接单片机失败。");
            }

            scmPort.DataReceived += new SerialDataReceivedEventHandler(this.SerialPort_DataReceived);
        }


        /// <summary>
        /// 化收发卡一体机---串口操作句柄
        /// </summary>
        public UInt32 Hdle = 0;

        public string CardDispenser_PORTNAME;
        public int CardDispenser_BAUDRATE;

        /// <summary>
        /// 初始化收发卡一体机
        /// </summary>
        private void InitCRT591MR01()
        {
            CardDispenser_PORTNAME= SystemParam.SendSerialPortName;
            CardDispenser_BAUDRATE = SystemParam.SendBaudRate;
            try
            {
                Hdle = GrantCardClient.CommOpenWithBaut(CardDispenser_PORTNAME, (uint)Convert.ToUInt32(CardDispenser_BAUDRATE));
                if (Hdle != 0)
                {
                    SimpleConsole.WriteOprateLog($"发卡机串口打开成功，设备句柄为{Hdle}。", this);
                    //初始化发卡机
                    string msg;
                    if (GrantCardClient.InitCard(Hdle, "00", out msg))
                    {
                        if (SystemParam.TestPage == 1)
                        {
                            SimpleConsole.WriteOprateLog($"InitCard：发卡机返回数据" + msg, this);
                        }
                        //根据初始化结果来进行下一步的操作：
                        int index_1 = msg.IndexOf(":");
                        string st0 = msg.Substring(index_1 + 1, 1);
                        string st1 = msg.Substring(index_1 + 2, 1);
                        string st2 = msg.Substring(index_1 + 3, 1);
                        //卡机通道--有卡，则移到卡槽
                        if (st0 == "1" || st0 == "2")
                        {
                            string msg2 = "";
                            //移进来直接放到卡槽内
                            if (GrantCardClient.MoveCardToRecycleBin(Hdle, "00", out msg2))
                            {
                                int index_02 = msg.IndexOf(":");
                                if (index_1 >= 0)
                                {
                                    string st0_2 = msg2.Substring(index_02 + 1, 1);
                                    string st1_2 = msg2.Substring(index_02 + 2, 1);
                                    string st2_2 = msg2.Substring(index_02 + 3, 1);
                                    if (st2_2 == "1")
                                    {
                                        VoiceHelper.Speak("回收箱卡满,请处联系工作人员处理。");
                                        MessageBox.Show("回收箱卡满,请处联系工作人员处理。");
                                    }
                                }
                            }
                        }

                        //发卡箱
                        if (st1 == "0")
                        {
                            VoiceHelper.Speak("卡箱无卡,请联系工作人员处理。");
                            MessageBox.Show("卡箱无卡,请联系工作人员处理。");
                        }
                        if (st1 == "1")
                        {
                            VoiceHelper.Speak("卡箱卡少,请联系工作人员处理。");
                            MessageBox.Show("卡箱卡少,请联系工作人员处理。");
                        }
                        //回收箱
                        if (st2 == "1")
                        {
                            VoiceHelper.Speak("回收箱卡满,请联系工作人员处理。");
                            MessageBox.Show("回收箱卡满,请联系工作人员处理。");
                        }
                        SimpleConsole.WriteInfo("发卡机-初始化成功！" + msg, this);
                    }
                    else
                    {
                        int index_1 = msg.IndexOf("错误信息:");
                        if (index_1 < 0)
                        {
                            VoiceHelper.Speak("卡机-初始化失败。"+ msg);
                            MessageBox.Show("卡机-初始化失败," + msg);
                            SimpleConsole.WriteInfo("发卡机-初始化失败！" + msg, this);
                        }
                        string msgInfo = msg.Substring(index_1 + 5);
                        VoiceHelper.Speak("卡机-初始化失败。");
                        MessageBox.Show("卡机-初始化失败," + msgInfo);
                        SimpleConsole.WriteInfo("卡机-初始化失败！" + msg, this);
                        return;
                    }
                    //2.初始化后的操作----------------------------------------------------------------------------
                    //比如已经有卡在那个发卡位置
                }
                else
                {
                    this.Alert("提示", "发卡机串口打开失败。");
                    //要通知到相应的标志里面去
                    SimpleConsole.WriteInfo("发卡机串口打开失败。", this);
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("发卡机串口打开出错。" + ex.ToString(), this);
                this.Alert("出错", "发卡机串口打开出错。");
            }
        }

        private SerialPort controllerPort = null;

        public string CONTROLLER_PORTNAME;
        public int CONTROLLER_BAUDRATE;
        private byte[] controllerState = new byte[] { 0xAA, 0xB4, 0x01, 0x00, 0x00, 0x00, 0x00, 0xdd };


        public void SendMsgToController(byte[] msg)
        {

            this.scmOutputWindow.SetSend(convertString16(msg));
            if (this.controllerPort != null && this.controllerPort.IsOpen)
            {
                this.controllerPort.Write(msg, 0, msg.Length);
            }
        }


        /// <summary>
        /// 初始化单片机通信
        /// </summary>
        private void InitController()
        {
            this.controllerPort = new SerialPort();
            controllerPort.BaudRate = CONTROLLER_BAUDRATE;
            controllerPort.PortName = CONTROLLER_PORTNAME;

            try
            {
                controllerPort.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("连接控制器失败。");
            }

        }

        public void SetController(int index, byte value)
        {
            this.controllerState[index + 2] = value;
            this.SendMsgToController(this.controllerState);
        }





        private LinkedList<byte[]> splitCommand1(byte[] command)
        {
            LinkedList<byte[]> resultList = new LinkedList<byte[]>();
            string commandString = System.Text.Encoding.Default.GetString(command);
            while (commandString.IndexOf("$") > -1)
            {
                int commandStart = commandString.IndexOf("$");
                int commandLength = commandString.IndexOf("\r\n") + 2 - commandStart;
                byte[] tempCommand = System.Text.Encoding.Default.GetBytes(commandString.Substring(commandStart, commandLength));
                resultList.AddLast(tempCommand);
                commandString = commandString.Substring(commandLength);
            }
            return resultList;
        }

        private LinkedList<byte[]> splitCommand(byte[] command)
        {
            LinkedList<byte[]> resultList = new LinkedList<byte[]>();
            int index = 0;
            while (index < command.Length)
            {
                if (command[index] == 0x24)
                {
                    for (int i = index; i < command.Length - 1; i++)
                    {
                        if (command[i] == 0x0d && command[i + 1] == 0x0a)
                        {
                            byte[] tempCommand = new byte[i - index + 2];
                            for (int j = 0; j < i - index + 2; j++)
                            {
                                tempCommand[j] = command[index + j];
                            }

                            resultList.AddLast(tempCommand);
                            index = i + 2;
                            break;
                        }
                    }
                }
            }
            return resultList;
        }


        private string convertString16(byte[] command)
        {
            string result = "";
            foreach (byte b in command)
            {
                string c = string.Format("{0:X}", b);
                if (c.Length == 1)
                {
                    c = "0" + c;
                }
                result += " " + c;
            }
            return result;
        }




        private LinkedList<byte> dataList = new LinkedList<byte>();

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[this.scmPort.BytesToRead];
            this.scmPort.Read(ReDatas, 0, ReDatas.Length);//读取数据

            lock (this.dataList)
            {
                foreach (var b in ReDatas)
                {
                    this.dataList.AddLast(b);
                }

                while (this.dataList.Count >= 7)
                {
                    int startIndex = 0;
                    int endIndex = 0;

                    for (int i = 0; i < this.dataList.Count; i++)
                    {
                        if (this.dataList.ElementAt(i) == 0x24)
                        {
                            startIndex = i;
                            continue;
                        }
                        if (i >= 1 && this.dataList.ElementAt(i) == 0x0a && this.dataList.ElementAt(i - 1) == 0x0d)
                        {
                            endIndex = i;
                            break;
                        }
                    }
                    if (endIndex > 1)
                    {
                        var command = new byte[endIndex + 1];
                        for (int i = 0; i < endIndex + 1; i++)
                        {
                            command[i] = this.dataList.First();
                            this.dataList.RemoveFirst();
                        }
                        handleCommand(command);
                    }
                    else
                    {
                        break;
                    }
                }
            }



            //var commandList = splitCommand(ReDatas);
            //foreach (byte[] command in commandList)
            //{
            //    handleCommand(command);
            //}
        }

        public void handleCommand(byte[] ReDatas)
        {

            if (ReDatas.Length == 18)
            {
                if (this.scmStep!= ScmStep.PRINT_DRIVING_LICENSE_BARCODE_READY)
                {
                    return;
                }
            }


            SimpleConsole.WriteInfo(string.Format("接收命令:{0}", convertString16(ReDatas)), this);

            //移动完成
            if (ComCommand.equals(ReDatas, new byte[] { 0x24, 0x16, 0x18, 0xd1, 0x00, 0x0d, 0x0a }, new byte[] { 0x24, 0x16, 0x18, 0xd1, 0x01, 0x0d, 0x0a }, new byte[] { 0x24, 0x16, 0x18, 0xd1, 0x02, 0x0d, 0x0a }))
            {
                System.Threading.Thread.Sleep(1000);
                //this.cameraPage.MoveCompleted(ReDatas[4]);
                return;
            }


            if (ComCommand.equals(ReDatas, ComCommand.CAMERA_SELF_CHECKING_COMPLETE))
            {
                SimpleConsole.WriteInfo("相机自检完成", this);
                return;
            }

            if (ComCommand.equals(ReDatas, ComCommand.COMMUNICATION_CHECKING_SUCCESSED))
            {
                this.communicationFailedCount = 0;
                return;
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //指令传递给单片机失败
            if (ComCommand.equals(ReDatas, ComCommand.COMMUNICATION_CHECKING_FAILED))
            {
                if (this.communicationFailedCount < 3)
                {

                    this.communicationFailedCount++;

                    SendMsgToScm(lastCommand);//重发一遍

                }
                else
                {
                    this.errorFlag = true;
                    MessageBox.Show("工控机与单片机通信坏:0x24, 0x33, 0x13, 0xB9, 0x34, 0x0d, 0x0a");

                }
                return;
            }


            this.scmOutputWindow.SetReceive(convertString16(ReDatas));


            if (ComCommand.equals(ReDatas, ComCommand.COMMUNICATION_CHECKING_SUCCESSED))
            {
                return;
            }

            if (ReDatas.Length == 18 && this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_BARCODE_READY)
            {
                return;
            }


            switch (this.scmStep)
            {
                //检查通信状态
                case ScmStep.START_COMMUNICATION_CHECKING:
                    if (ComCommand.equals(ReDatas, ComCommand.START_COMMUNICATION_CHECKING, ComCommand.COMMUNICATION_CHECKING_SUCCESSED))
                    {
                        this.scmStep = ScmStep.SELF_CHECK_COMMUNICATION_CHECKING_SUCCESSED;
                    }
                    else
                    {
                        setScmError(ReDatas);
                        this.scmStep = ScmStep.SELF_CHECK_COMMUNICATION_CHECKING_FAILED;
                    }
                    manual.Set();
                    break;
                //单片机自检
                case ScmStep.START_SCM_SELF_CHECKING:
                    if (ComCommand.equals(ReDatas, ComCommand.SCM_SELF_CHECKING_SUCCESSED))
                    {
                        //MessageBox.Show("单片机自检成功");
                        this.scmStep = ScmStep.SCM_SELF_CHECKING_SUCCESSED;
                    }
                    else
                    {
                        //MessageBox.Show("单片机自检失败");
                        setScmError(ReDatas);
                        this.scmStep = ScmStep.SCM_SELF_CHECKING_FAILD;
                    }
                    manual.Set();
                    break;
                //GMC自检状态
                case ScmStep.START_GMC_SELF_CHECKING:
                    if (ComCommand.equals(ReDatas, ComCommand.GMC_SELF_CHECKING_SUCCESSED))
                    {
                        //MessageBox.Show("GMC自检成功");
                        this.scmStep = ScmStep.GMC_SELF_CHECKING_SUCCESSED;
                    }
                    else
                    {
                        setScmError(ReDatas);
                        this.scmStep = ScmStep.GMC_SELF_CHECKING_FAILD;
                    }
                    manual.Set();
                    break;
                //开始打印留念免检
                case ScmStep.PRINT_LNMJ_START:
                    //送入打印位置
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_LNMJ_PRINTER_READY))
                    {
                        this.scmStep = ScmStep.PRINT_LNMJ_PRINTER_READY;
                        manual.Set();
                    }
                    //通信正常 或 GMC准备就绪
                    else if (ComCommand.equals(ReDatas, ComCommand.COMMUNICATION_CHECKING_SUCCESSED, ComCommand.PRINT_LNMJ_GMC_READY))
                    {
                        //无操作
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;

                case ScmStep.PRINT_LNMJ_PRINT_COMPLETED:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_LNMJ_ALL_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_LNMJ_ALL_COMPLETED;
                    }
                    else
                    {
                        setScmError(ReDatas);
                    }
                    manual.Set();
                    break;
                //
                case ScmStep.PRINT_DRIVING_LICENSE_START:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_BARCODE_PREPARE))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_BARCODE_READY;
                    }
                    else if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_GMC_READY, ComCommand.PRINT_DRIVING_LICENSE_MATERIAL_READY))
                    {
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_BARCODE_READY:

                    if (ReDatas.Length == 18)
                    {
                        string zxbh = System.Text.Encoding.Default.GetString(ReDatas).Substring(2, 13);
                        this.businessInfo.zxbh = zxbh;
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_BARCODE_RIGHT;
                        this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_BARCODE_RIGHT);
                        //this.businessInfo.zxbh = zxbh;
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_BARCODE_RIGHT:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_BARCODE_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_BARCODE_COMPLETED;
                        manual.Set();
                    }
                    else if (ReDatas.Length == 18)
                    {

                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_WAIT_EPSON:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_EPSON_START))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_EPSON_READY;
                    }
                    else
                    {
                        setScmError(ReDatas);
                    }
                    manual.Set();
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_EPSON_PRINT_COMPLETED:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_START))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_FRONT_READY;
                        manual.Set();
                    }
                    else if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_EPSON_PROCESS_COMPLETED))
                    {

                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_FRONT_COMPLETED:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK_OR_NOT))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK_OR_NOT;
                        manual.Set();
                    }
                    else if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_FRONT_COMPLETED))
                    {

                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_START:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_START))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_READY;
                        manual.Set();
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }

                    break;

                case ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_ALL_COMPLETED;
                        manual.Set();
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;

                case ScmStep.PRINT_DRIVING_LICENSE_WAIT_CUT:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_CUT_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_WAIT_PACKAGE;
                        manual.Set();
                    }
                    else if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_ALL_COMPLETED, ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED))
                    {

                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_WAIT_PACKAGE:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_PACKAGE_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_WAIT_ALL_COMPLETED;
                        manual.Set();
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
                case ScmStep.PRINT_DRIVING_LICENSE_WAIT_ALL_COMPLETED:
                    if (ComCommand.equals(ReDatas, ComCommand.PRINT_DRIVING_LICENSE_ALL_COMPLETED))
                    {
                        this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_ALL_COMPLETED;
                        manual.Set();
                    }
                    else
                    {
                        setScmError(ReDatas);
                        manual.Set();
                    }
                    break;
            }
        }



        private void setScmError(byte[] data)
        {

            string message = "发生异常：" + convertString16(data) + "\r\n";

            if (ComCommand.equals(data, new byte[] { 0x1 })) { message += "异常描述:"; }


            if (ComCommand.equals(data, new byte[] { 0x24, 0x13, 0x13, 0xD9, 0x01, 0x0d, 0x0a })) { message += "异常描述:吸料错误，气泵坏"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x07, 0x13, 0xE5, 0x4E, 0x0d, 0x0a })) { message += "异常描述:未进入富士通打印位"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2A, 0x13, 0xC2, 0x38, 0x0d, 0x0a })) { message += "异常描述:富士通未打印成功"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2B, 0x13, 0xC1, 0x29, 0x0d, 0x0a })) { message += "异常描述:富士通取出失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x14, 0x13, 0xD8, 0x02, 0x0d, 0x0a })) { message += "异常描述:测厚设备故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x15, 0x13, 0xD7, 0x03, 0x0d, 0x0a })) { message += "异常描述:吸取多张纸"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x17, 0x13, 0xD5, 0x06, 0x0d, 0x0a })) { message += "异常描述:转头设备故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2D, 0x13, 0xBF, 0x2B, 0x0d, 0x0a })) { message += "异常描述:EPSON未打印成功"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2E, 0x13, 0xBE, 0x2C, 0x0d, 0x0a })) { message += "异常描述:EPSON出纸故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x07, 0x13, 0xE5, 0x4E, 0x0d, 0x0a })) { message += "异常描述:未进入富士通打印位"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2A, 0x13, 0xC2, 0x38, 0x0d, 0x0a })) { message += "异常描述:富士通未打印成功"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x2B, 0x13, 0xC1, 0x29, 0x0d, 0x0a })) { message += "异常描述:富士通取出失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x1C, 0x13, 0xD0, 0x1B, 0x0d, 0x0a })) { message += "异常描述:翻证设备故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x1D, 0x13, 0xCF, 0x1C, 0x0d, 0x0a })) { message += "异常描述:翻页失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x1E, 0x13, 0xCE, 0x1D, 0x0d, 0x0a })) { message += "异常描述:翻页后吸取失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x20, 0x13, 0xCC, 0x1F, 0x0d, 0x0a })) { message += "异常描述:未进入切割位"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x22, 0x13, 0xCA, 0x21, 0x0d, 0x0a })) { message += "异常描述:夹子设备故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x25, 0x13, 0xC7, 0x23, 0x0d, 0x0a })) { message += "异常描述:塑封膜放入失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x26, 0x13, 0xC6, 0x25, 0x0d, 0x0a })) { message += "异常描述:证件入膜失败"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x22, 0x13, 0xCA, 0x21, 0x0d, 0x0a })) { message += "异常描述:夹子设备故障"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x27, 0x13, 0xC5, 0x26, 0x0d, 0x0a })) { message += "异常描述:证件未放入覆膜机"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x28, 0x13, 0xC4, 0x27, 0x0d, 0x0a })) { message += "异常描述:副页未拿走"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x29, 0x13, 0xC3, 0x28, 0x0d, 0x0a })) { message += "异常描述:取皮套失败"; }

            if (ComCommand.equals(data, new byte[] { 0x24, 0x31, 0x13, 0xBB, 0x32, 0x0d, 0x0a })) { message += "异常描述:工控机串口坏"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x32, 0x13, 0xBA, 0x33, 0x0d, 0x0a })) { message += "异常描述:单片机串口坏"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x33, 0x13, 0xB9, 0x34, 0x0d, 0x0a })) { message += "异常描述:工控机与单片机通信坏"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x12, 0x13, 0xDA, 0x31, 0x0d, 0x0a })) { message += "异常描述:GMC串口坏"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x34, 0x13, 0xB8, 0x35, 0x0d, 0x0a })) { message += "异常描述:通信异常"; }

            if (ComCommand.equals(data, new byte[] { 0x24, 0x2F, 0x13, 0xBD, 0x2D, 0x0d, 0x0a })) { message += "异常描述:工位有异物"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x0E, 0x13, 0xDE, 0x45, 0x0d, 0x0a })) { message += "异常描述:驾驶证纸用完"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x0F, 0x13, 0xDD, 0x46, 0x0d, 0x0a })) { message += "异常描述:机械手不在原点"; }

            if (ComCommand.equals(data, new byte[] { 0x24, 0x0B, 0x13, 0xE1, 0x00, 0x0d, 0x0a })) { message += "异常描述:单片机需复位"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x08, 0x13, 0xE4, 0x40, 0x0d, 0x0a })) { message += "异常描述:皮套缺料"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x09, 0x13, 0xE3, 0x41, 0x0d, 0x0a })) { message += "异常描述:年检贴(1号仓)缺料"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x09, 0x13, 0xE3, 0x42, 0x0d, 0x0a })) { message += "异常描述:年检贴(2号仓)缺料"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x09, 0x13, 0xE3, 0x43, 0x0d, 0x0a })) { message += "异常描述:年检贴(3号仓)缺料"; }
            if (ComCommand.equals(data, new byte[] { 0x24, 0x1A, 0x13, 0xD2, 0x42, 0x0d, 0x0a })) { message += "异常描述:塑封膜缺料"; }
            SimpleConsole.WriteError(message, this);
            //MessageBox.Show(message);

            this.Alert("异常", message,delegate() {
                this.ResetIndex();
            });

            //MessageBox.Show("异常:"+convertString16(data));
        }



        private ScmStep scmStep;

        private ManualResetEvent manual = new ManualResetEvent(false);

        public void SendMsgToScm(byte[] msg)
        {

            this.lastCommand = msg;
            this.scmOutputWindow.SetSend(convertString16(msg));
            if (scmPort != null && scmPort.IsOpen)
            {
                this.scmPort.Write(msg, 0, msg.Length);
            }
            SimpleConsole.WriteInfo(string.Format("发送命令:{0}", convertString16(msg)), this);

        }


        private bool waitOne(int time)
        {
            this.manual.Reset();
            return !this.manual.WaitOne(time);
        }







        public void SCMSelfChecking()
        {

            new Thread(new ThreadStart(delegate ()
            {
                bool timeoutFlag = false;

                //检查通讯情况
                //this.scmStep = ScmStep.START_COMMUNICATION_CHECKING;
                //SendMsgToScm(ComCommand.START_COMMUNICATION_CHECKING);

                //timeoutFlag = this.waitOne(10000);
                //if (timeoutFlag)
                //{
                //    SimpleConsole.WriteInfo("自检检查通信-通信超时", this);
                //    return;
                //}
                //if (this.scmStep != ScmStep.SELF_CHECK_COMMUNICATION_CHECKING_SUCCESSED)
                //{
                //    SimpleConsole.WriteInfo("自检检查通信-通信异常", this);
                //    return;
                //}

                this.scmStep = ScmStep.START_SCM_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_SCM_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("单片机自检-通信超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.SCM_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("单片机自检-自检异常", this);
                    MessageBox.Show("单片机自检异常");

                    return;
                }
                //MessageBox.Show("单片机自检正常");

                this.scmStep = ScmStep.START_GMC_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_GMC_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("GMC自检-通讯超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.GMC_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("GMC自检-自检异常", this);
                    MessageBox.Show("GMC自检异常");
                    return;
                }
                MessageBox.Show("GMC自检正常");

            }))
            { IsBackground = true }.Start();
        }


        private int lnmjIndex = 0;

        public void PrintLnmj(string lsh)
        {

            if (!this.printProcessPage.loginFlag)
            {
                this.ShowVerifyCode(lsh);
                return;
            }

            this.printProcessPage.InitPage();
            this.printProcessPage.ResetProcess();
            this.showPage(this.printProcessPage);

            new Thread(new ThreadStart(delegate ()
            {
                bool timeoutFlag = false;

                //检查通信
                //this.scmStep = ScmStep.START_COMMUNICATION_CHECKING;
                //SendMsgToScm(ComCommand.START_COMMUNICATION_CHECKING);
                //timeoutFlag = this.waitOne(10000);
                //if (timeoutFlag)
                //{
                //    SimpleConsole.WriteInfo("打印6年免检-检查通信-通信超时", this);
                //    return;
                //}
                //if (this.scmStep != ScmStep.SELF_CHECK_COMMUNICATION_CHECKING_SUCCESSED)
                //{
                //    SimpleConsole.WriteInfo("打印6年免检-检查通信-通信异常", this);
                //    return;
                //}

                this.scmStep = ScmStep.START_SCM_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_SCM_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("单片机自检-通信超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.SCM_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("单片机自检-自检异常", this);
                    //MessageBox.Show("单片机自检异常");

                    return;
                }
                SimpleConsole.WriteInfo("打印驾驶证-单片机自检-通信正常", this);

                this.scmStep = ScmStep.START_GMC_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_GMC_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("GMC自检-通讯超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.GMC_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("GMC自检-自检异常", this);
                    return;
                }
                SimpleConsole.WriteInfo("打印驾驶证-GMC自检-通信正常", this);

                //MessageBox.Show("打印6年免检-通信正常");
                this.printProcessPage.setProcess(10, 20);

                //发送开始打印命令
                this.scmStep = ScmStep.PRINT_LNMJ_START;
                byte[] startCommand = ComCommand.PRINT_LNMJ_START;


                //模拟三个料仓
                startCommand[4] = (byte)this.businessInfo.lnmjIndex;
                //lnmjIndex++;
                this.SendMsgToScm(startCommand);
                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印6年免检-开始打印-通信超时", this);
                    return;
                }
                //打印机未就绪
                if (this.scmStep != ScmStep.PRINT_LNMJ_PRINTER_READY)
                {
                    SimpleConsole.WriteInfo("打印6年免检-打印机未就绪", this);
                    return;
                }
                this.printProcessPage.setProcess(50, 10);


                //打印机就绪 开始打印

               bool printFlag=  this.StartPrintLnmj(lsh);

                while (!printFlag)
                {
                    bool retryFlag = false;

                    this.Confirm("提示", "六合一系统网络异常，打印终止。请重试。", "重试", "取消", delegate () {
                        printFlag = this.StartPrintLnmj(lsh);
                        retryFlag = true;
                        manual.Set();

                    }, delegate () {
                        this.PrintVoidLogo();
                        this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED);
                        this.ResetIndex();
                        retryFlag = false;
                        manual.Set();
                    });

                    timeoutFlag = this.waitOne(120000);
                    if (timeoutFlag)
                    {
                        this.Alert("提示", "操作超时。", delegate () {
                            this.PrintVoidLogo();
                            this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED);
                            this.ResetIndex();
                        });
                        return;
                    }
                    if (!retryFlag)
                    {
                        return;
                    }
                }

                this.printProcessPage.setProcess(90, 5);

                //发送打印完成命令
                this.scmStep = ScmStep.PRINT_LNMJ_PRINT_COMPLETED;
                this.SendMsgToScm(ComCommand.PRINT_LNMJ_PRINT_COMPLETED);
                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印6年免检-打印完成-通信超时", this);
                    return;
                }
                //未取出成功
                if (this.scmStep != ScmStep.PRINT_LNMJ_ALL_COMPLETED)
                {
                    SimpleConsole.WriteInfo("打印6年免检-未成功完成", this);
                    return;
                }
                //打印完成提示用户取走证件
                this.printProcessPage.setProcess(100, 0);

                Thread.Sleep(1000);
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_PUSH_OFF);
                Thread.Sleep(1000);
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_PUSH_OFF_CLOSE);
                this.appStep = AppStep.TICKET_RESULT;

            }))
            { IsBackground = true }.Start();
        }

        public void PrintDrivingLicence(string lsh)
        {
            //if (!this.printProcessPage.loginFlag)
            //{
            //    this.ShowVerifyCode(lsh);
            //    return;
            //}
            this.printProcessPage.InitPage();
            this.printProcessPage.ResetProcess();

            this.showPage(printProcessPage);
            new Thread(new ThreadStart(delegate ()
            {


                bool timeoutFlag = false;

                //检查通信
                //this.scmStep = ScmStep.START_COMMUNICATION_CHECKING;
                //SendMsgToScm(ComCommand.START_COMMUNICATION_CHECKING);
                //timeoutFlag = this.waitOne(100000);

                //if (timeoutFlag)
                //{
                //    SimpleConsole.WriteInfo("打印驾驶证-检查通信-通信超时", this);
                //    return;
                //}
                //if (this.scmStep != ScmStep.SELF_CHECK_COMMUNICATION_CHECKING_SUCCESSED)
                //{
                //    SimpleConsole.WriteInfo("打印驾驶证-检查通信-通信异常" + this.scmStep.ToString(), this);
                //    return;
                //}
                //SimpleConsole.WriteInfo("打印驾驶证-检查通信-通信正常", this);


                this.scmStep = ScmStep.START_SCM_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_SCM_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("单片机自检-通信超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.SCM_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("单片机自检-自检异常", this);
                    //MessageBox.Show("单片机自检异常");

                    return;
                }
                SimpleConsole.WriteInfo("打印驾驶证-单片机自检-通信正常", this);

                this.scmStep = ScmStep.START_GMC_SELF_CHECKING;
                SendMsgToScm(ComCommand.START_GMC_SELF_CHECKING);
                timeoutFlag = this.waitOne(10000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("GMC自检-通讯超时", this);
                    return;
                }
                if (this.scmStep != ScmStep.GMC_SELF_CHECKING_SUCCESSED)
                {
                    SimpleConsole.WriteInfo("GMC自检-自检异常", this);
                    return;
                }
                SimpleConsole.WriteInfo("打印驾驶证-GMC自检-通信正常", this);



                this.printProcessPage.setProcess(10, 90);

                //发送开始打印命令
                this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_START;
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_START);
                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-开始打印-通信超时", this);
                    return;
                }
                //未收到条形码
                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_BARCODE_COMPLETED)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-未正常收到条形码", this);
                    return;
                }
                this.printProcessPage.setProcess(20, 80);
                this.PreparePrintPhoto();
                //等待EPSON就绪
                this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_WAIT_EPSON;
                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印6年免检-等待EPSON-超时", this);
                    return;
                }

                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_EPSON_READY)
                {
                    SimpleConsole.WriteInfo("打印6年免检-等待EPSON-打印机未就绪", this);
                    return;
                }

                //打印机就绪 开始打印照片
                this.CheckPrintPhoto();
                this.printProcessPage.setProcess(30, 70);

                //发送EPSON打印完成命令
                this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_EPSON_PRINT_COMPLETED;
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_EPSON_PRINT_COMPLETED);

                timeoutFlag = this.waitOne(100000);

                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-发送EPSON打印完成-通信超时", this);
                    return;
                }

                //富士通打印机未就绪
                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_FRONT_READY)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-打印正面-打印机未就绪", this);
                    return;
                }
                //富士通打印机就绪 打印正面


                bool printFlag = this.PrintLicenceFront(this.businessInfo.zxbh, lsh);

                while (!printFlag)
                {
                    bool retryFlag = false;
                    this.Confirm("提示", "六合一系统网络异常，打印终止。请重试。","重试","取消", delegate () {
                        printFlag = this.PrintLicenceFront(this.businessInfo.zxbh, lsh);
                        retryFlag = true;
                        manual.Set();

                    }, delegate () {
                        this.PrintVoidLogo();
                        this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED);
                        this.ResetIndex();
                        retryFlag = false;
                        manual.Set();
                    });

                    timeoutFlag = this.waitOne(120000);
                    if (timeoutFlag)
                    {
                        this.Alert("提示", "操作超时。", delegate () {
                            this.PrintVoidLogo();
                            this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED);
                            this.ResetIndex();
                        });
                        return;
                    }
                    if (!retryFlag)
                    {
                        return;
                    }
                }


                this.printProcessPage.setProcess(40, 60);

                this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_FRONT_COMPLETED;
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_COMPLETED);
                timeoutFlag = this.waitOne(100000);

                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-正面打印完成-通信超时", this);
                    return;
                }

                //询问是否打印正面
                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK_OR_NOT)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-询问是否打印正面-错误", this);
                    return;
                }

                bool printBackFlag = PrintUtil.printBackFlag;

                if (printBackFlag)
                {
                    this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_START;
                    this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK);
                    this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK);
                    timeoutFlag = this.waitOne(100000);

                    if (timeoutFlag)
                    {
                        SimpleConsole.WriteInfo("打印驾驶证-开始打印反面-通信超时", this);
                        return;
                    }


                    if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_READY)
                    {
                        SimpleConsole.WriteInfo("打印驾驶证-打印反面-打印机未就绪", this);
                        return;
                    }
                    //打印反面
                    this.PrintLicenceBack();

                    this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED;
                    this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_PRINT_COMPLETED);
                    timeoutFlag = this.waitOne(100000);
                    if (timeoutFlag)
                    {
                        SimpleConsole.WriteInfo("打印驾驶证-打印反面完成-通信超时", this);
                        return;
                    }

                    if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_FUJITSU_ALL_COMPLETED)
                    {
                        SimpleConsole.WriteInfo("打印驾驶证-打印反面-打印异常", this);
                        return;
                    }
                }
                else
                {
                    this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_NOT_PRINT_BACK);
                    this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_FUJITSU_NOT_PRINT_BACK);
                }

                this.printProcessPage.setProcess(60, 40);

                this.scmStep = ScmStep.PRINT_DRIVING_LICENSE_WAIT_CUT;
                timeoutFlag = this.waitOne(100000);

                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待切割-超时", this);
                    return;
                }

                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_WAIT_PACKAGE)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待切割-异常", this);
                    return;
                }
                this.printProcessPage.setProcess(70, 30);

                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待覆膜-超时", this);
                    return;
                }

                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_WAIT_ALL_COMPLETED)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待覆膜-异常", this);
                    return;
                }

                this.printProcessPage.setProcess(80, 20);


                timeoutFlag = this.waitOne(100000);
                if (timeoutFlag)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待制证完成-超时", this);
                    return;
                }

                if (this.scmStep != ScmStep.PRINT_DRIVING_LICENSE_ALL_COMPLETED)
                {
                    SimpleConsole.WriteInfo("打印驾驶证-等待制证完成-异常", this);
                    return;
                }
                this.printProcessPage.setProcess(90, 10);


                Thread.Sleep(2000);

                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_PUSH_OFF);



                //打印完成提示用户取走证件
                this.printProcessPage.setProcess(100, 0);

                Thread.Sleep(2000);
                this.SendMsgToScm(ComCommand.PRINT_DRIVING_LICENSE_PUSH_OFF_CLOSE);
                this.appStep = AppStep.TICKET_RESULT;

            }))
            { IsBackground = true }.Start();
        }


        private void Window_Closing(object sender, CancelEventArgs e)
        {
            //处理相关硬件
            //关闭发卡机串口
            try
            {
                if (Hdle != 0)
                {
                    int i = GrantCardClient.CommClose(Hdle);
                    Hdle = 0;
                    SimpleConsole.WriteInfo("退出-关闭发卡机串口-成功", this);
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("退出-关闭发卡机串口-出错" + ex.ToString(), this);
            }
            
            //this.cameraPage.DisConnect();
        }

        #region 六合一打印

        private object locker = new object();



        public void ShowVerifyCode(string lsh)
        {
            try
            {
                System.Drawing.Image verifyCodeImage = this.printProcessPage.GetVerifyCode(IP_ADDRESS);
                this.verifyCodeInputPage.InitPage(verifyCodeImage, lsh);
                this.showPage(verifyCodeInputPage);
            }
            catch (Exception)
            {
                try
                {
                    System.Drawing.Image verifyCodeImage = this.printProcessPage.GetVerifyCode(IP_ADDRESS);
                    this.verifyCodeInputPage.InitPage(verifyCodeImage, lsh);
                    this.showPage(verifyCodeInputPage);
                }
                catch (Exception e)
                {
                    this.Alert("提示", "网络异常,获取验证码失败。",delegate() {
                        this.ResetIndex();
                    });
                }
            }
        }

        public bool Login(string verifyCode)
        {
            return this.printProcessPage.Login(verifyCode, USER_NAME, PASSWORD);
        }

        public void ShowLoading() {
            this.loading = true;
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.grdLoading.Visibility = Visibility.Visible;
            }));
        }

        public void HideLoading()
        {
            this.loading = false;
            this.Dispatcher.Invoke(new Action(delegate ()
            {
                this.grdLoading.Visibility = Visibility.Hidden;
            }));
        }




        #endregion 六合一打印

        private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.idelTime = 0;
            e.Handled = true;
        }

        private void canvasFrame_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            if (!navigating)
            {
                e.Cancel = true;
            }
        }
        /// <summary>
        /// --?导航
        /// </summary>
        private bool navigating = false;

        private void canvasFrame_Navigated(object sender, NavigationEventArgs e)
        {
            navigating = false;
        }

        /// <summary>
        /// 退出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnQuit_Click(object sender, RoutedEventArgs e)
        {
            SimpleConsole.WriteInfo("当前用户点击了退出按钮", this);
            SimpleConsole.WriteQuitLog("当前用户点击了退出按钮", this);
            if (ShowConfirm("是否确认退出？"))
            {
                SimpleConsole.WriteQuitLog("在弹出框里，用户选择了【确定按钮】", this);
                SimpleConsole.WriteQuitLog("退出系统", this);
                
                SimpleConsole.WriteInfo("退出系统", this);
                //需要做的几件事
                //关闭自助机、关闭读卡器，身份识别


                //MXIO.MXEIO_Disconnect(hConnection);
                //MXIO.MXEIO_Exit();
                ////退出所有车牌识别
                //eParking.CloseDevice();
                //Log.Info("退出系统");
                //退出
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 弹出确认框并返回值
        /// </summary>
        /// <param name="showMsg"></param>
        /// <returns></returns>
        private bool ShowConfirm(string showMsg)
        {
            AllInOne.MainPages.Confirm confirm = new AllInOne.MainPages.Confirm(showMsg, AllInOne.Classes.SystemParam.CountDownConfirm);
            return confirm.ShowDialog() ?? false;
        }

        private void Btn_Setting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //设置窗口弹出来前是先登录
                Window view = new SystemSetWin();
                if (view != null)
                {
                    view.Owner = this;
                    view.ShowInTaskbar = false;
                    view.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    view.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                //SimpleConsole.WriteInfo("Btn_Setting_Click-出错" + ex.ToString(), this);
            }


            //Login login = new Login();
            //login.ShowDialog();
            //if (!login.DialogResult.Value) { login.Close(); }
            ////.Close();
            ////成功后再进入设置窗口
        }


        #region 二维码
        /// <summary>
        /// 功能：扫描二维码
        /// 日期：2023年1月30日
        /// </summary>
        public void StartRead_QR_Code()
        {
            this.ShowText("读取二维码信息");
            ReadQR_Code readQR_Code = new ReadQR_Code();
            bool? result = readQR_Code.ShowDialog();
            
            #region 【可删除】测试的将结果设有true
            if (SystemParam.TestPage == 1)
            {
                result = true;
            }
            #endregion

            if (result == true)
            {
                //获取制卡信息
                string str = readQR_Code.AuthCode;
                if (string.IsNullOrEmpty(str))
                {
                    this.Alert("提示", "  未读取到二维码信息。", new OkDelegate(delegate ()
                    {
                        return;
                    }));
                }
                //是不是json字符串
                #region 模拟已经过加密的二维码信息
                QRCodeInfoModel model = new QRCodeInfoModel();
                model.RegName = "王利鹏";
                model.IdentityNum = "410325199909290511";
                model.RegPhone = "15670752575";
                model.Plate = "蒙D1234B";
                model.GoodsName = "铜粉";
                model.Company = "济源市汇越矿产品有限公司";
                model.Receiver = "赤峰云铜电解厂";
                model.SenderTare = 0;
                model.SenderGross = 0;
                model.SenderNet = 27000;
                model.iCount = 1;
                model.DriverName2 = "张兴路";
                model.DriverPhone2 = "15670752575";
                model.CustomerType = "宁波和笙";
                //Json字符串
                string json = JsonConvert.SerializeObject(model);
                byte[] sourceData = Encoding.UTF8.GetBytes(json);
                System.Console.Out.WriteLine("加密: ");
                String cipherText = SM2Utils.Encrypt(Hex.Decode(pubk), sourceData);
                System.Console.Out.WriteLine(cipherText);
                str = cipherText;
                #endregion

                QRCodeInfoModel qRCodeInfoModel = Deal_QR_Info(str);
                if (qRCodeInfoModel == null)
                {
                    this.Alert("错误", "  未解析到二维码信息。", new OkDelegate(delegate ()
                    {
                        return;
                    }));
                }
                //【左下角】去掉读取二维码信息提示
                this.ShowText("");
                //调用入厂货物 制卡页面--并将制卡信息反填过去
                this.giveCard_Page.QRCode_InitPage(qRCodeInfoModel);
                this.showPage(giveCard_Page);
            }
            else
            {
                this.Alert("提示", "  未读取到二维码信息。", new OkDelegate(delegate ()
                {
                }));
            }
        }
        /// <summary>
        /// 功能：处理二维码信息
        /// 日期：2023年1月30日
        /// </summary>
        public QRCodeInfoModel Deal_QR_Info(string QR_Info)
        {
            try
            {
                //解密
                byte[] result = SM2Utils.Decrypt(Hex.Decode(prik), Hex.Decode(QR_Info));                
                string json = Encoding.UTF8.GetString(result);
                try
                {
                    return JsonConvert.DeserializeObject<QRCodeInfoModel>(json);
                }
                catch (Exception ex)
                {
                    SimpleConsole.WriteInfo("打码制卡-解密二维码信息1-出错" + ex.ToString(), this);
                }
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("打码制卡-解密二维码信息2-出错" + ex.ToString(), this);
            }
            return null;
        }
        #endregion


        #region 制卡信息框
        /// <summary>
        /// 功能：制卡信息框--未作选择
        /// 日期：2023年3月29日
        /// </summary>
        public void NoSelectTip()
        {
            try
            {
                this.Alert("提示", "  未读取到二维码信息。", new OkDelegate(delegate ()
                {
                    MessageBox.Show("选择了确定");
                }));
            }
            catch (Exception ex)
            {
                SimpleConsole.WriteInfo("制卡信息框--未作选择-出错" + ex.ToString(), this);
            }
        }
        #endregion

        #region 语音播报
        private void PlayVioce()
        {
            while (true)
            {
                try
                {
                    if (PlayVioceQueue.Count > 0)
                    {
                        VoiceHelper.Speak(PlayVioceQueue.Dequeue());
                    }
                }
                catch (Exception ex)
                {
                    SimpleConsole.WriteInfo("PlayVioce：" + ex.ToString(), null);
                }
                Thread.Sleep(200);
            }
        }
        #endregion

    }




    public enum AppStep
    {
        /// <summary>
        /// 首页
        /// </summary>
        INDEX = 0x000000,
        /// <summary>
        /// 驾驶证首页
        /// </summary>
        INDEX_DRIVING_LICENCE = 0x000010,
        /// <summary>
        /// 机动车首页
        /// </summary>
        INDEX_CAR = 0x000020,
        /// <summary>
        /// 等待放置身份证
        /// </summary>
        IDENTITY_VERIFY_STEP0 = 0x010000,
        /// <summary>
        /// 人证核验步骤1 提示刷二代身份证
        /// </summary>
        IDENTITY_VERIFY_STEP1 = 0x010010,
        /// <summary>
        /// 人证核验步骤2 人脸识别
        /// </summary>
        IDENTITY_VERIFY_STEP2 = 0x010020,
        /// <summary>
        /// 人证核验步骤3 比对成功
        /// </summary>
        IDENTITY_VERIFY_STEP3 = 0x010030,

        /// <summary>
        /// 人证核验步骤3 比对失败
        /// </summary>
        IDENTITY_VERIFY_STEP4 = 0x010040,

        /// <summary>
        /// 输入流水号
        /// </summary>
        INPUT_SERIAL_NUMBER = 0X050000,
        /// <summary>
        /// 小票结果
        /// </summary>
        /// 

        IDENTITY_VERIFY_STEP50 = 0x050000,
        /// <summary>
        /// 人证核验步骤1 提示刷二代身份证
        /// </summary>
        IDENTITY_VERIFY_STEP51 = 0x050010,
        /// <summary>
        /// 人证核验步骤2 人脸识别
        /// </summary>
        IDENTITY_VERIFY_STEP52 = 0x050020,
        /// <summary>
        /// 人证核验步骤3 比对成功
        /// </summary>
        IDENTITY_VERIFY_STEP53 = 0x050030,

        /// <summary>
        /// 人证核验步骤3 比对失败
        /// </summary>
        IDENTITY_VERIFY_STEP54 = 0x050040,

        /// <summary>
        /// 小票结果
        /// </summary>
        TICKET_RESULT = 0x090000,

        /// <summary>
        /// 打印中
        /// </summary>
        PRINT_PROCESS = 0x100000

    }

    /// <summary>
    /// 自助机软件的流程步骤
    /// </summary>
    public enum App_Step
    {
        /// <summary>
        /// 首页
        /// </summary>
        INDEX = 0x000000,
        /// <summary>
        /// 驾驶证首页
        /// </summary>
        INDEX_DRIVING_LICENCE = 0x000010,
        /// <summary>
        /// 机动车首页
        /// </summary>
        INDEX_CAR = 0x000020,
        /// <summary>
        /// 等待放置身份证
        /// </summary>
        IDENTITY_VERIFY_STEP0 = 0x010000,
        /// <summary>
        /// 人证核验步骤1 提示刷二代身份证
        /// </summary>
        IDENTITY_VERIFY_STEP1 = 0x010010,
        /// <summary>
        /// 人证核验步骤2 人脸识别
        /// </summary>
        IDENTITY_VERIFY_STEP2 = 0x010020,
        /// <summary>
        /// 人证核验步骤3 比对成功
        /// </summary>
        IDENTITY_VERIFY_STEP3 = 0x010030,

        /// <summary>
        /// 人证核验步骤3 比对失败
        /// </summary>
        IDENTITY_VERIFY_STEP4 = 0x010040,

        /// <summary>
        /// 输入流水号
        /// </summary>
        INPUT_SERIAL_NUMBER = 0X050000,
        /// <summary>
        /// 小票结果
        /// </summary>
        /// 

        IDENTITY_VERIFY_STEP50 = 0x050000,
        /// <summary>
        /// 人证核验步骤1 提示刷二代身份证
        /// </summary>
        IDENTITY_VERIFY_STEP51 = 0x050010,
        /// <summary>
        /// 人证核验步骤2 人脸识别
        /// </summary>
        IDENTITY_VERIFY_STEP52 = 0x050020,
        /// <summary>
        /// 人证核验步骤3 比对成功
        /// </summary>
        IDENTITY_VERIFY_STEP53 = 0x050030,

        /// <summary>
        /// 人证核验步骤3 比对失败
        /// </summary>
        IDENTITY_VERIFY_STEP54 = 0x050040,

        /// <summary>
        /// 小票结果
        /// </summary>
        TICKET_RESULT = 0x090000,

        /// <summary>
        /// 打印中
        /// </summary>
        PRINT_PROCESS = 0x100000,

        /// <summary>
        /// 录入信息发卡--第1步
        /// </summary>
        GIVE_INFOR_STEP11 = 0x110001,

        /// <summary>
        /// 录入信息发卡--第2步
        /// </summary>
        GIVE_INFOR_STEP12 = 0x110002,

        /// <summary>
        /// 录入信息发卡--第3步
        /// </summary>
        GIVE_INFOR_STEP13 = 0x110003,

        /// <summary>
        /// 录入信息发卡--第4步
        /// </summary>
        GIVE_INFOR_STEP14 = 0x110004,

        /// <summary>
        /// 录入信息发卡--第5步
        /// </summary>
        GIVE_INFOR_STEP15 = 0x110005,

    }


    public class ComCommand
    {

        /// <summary>
        /// 检查通讯情况
        /// </summary>
        public static byte[] START_COMMUNICATION_CHECKING = { 0x24, 0x07, 0x07, 0xF1, 0x77, 0x0d, 0x0a };

        /// <summary>
        /// 通信正常
        /// </summary>
        public static byte[] COMMUNICATION_CHECKING_SUCCESSED = { 0x24, 0x66, 0x66, 0x66, 0x66, 0x0d, 0x0a };

        /// <summary>
        /// 通信异常
        /// </summary>
        public static byte[] COMMUNICATION_CHECKING_FAILED = { 0x24, 0x22, 0x22, 0x22, 0x22, 0x0d, 0x0a };

        /// <summary>
        /// 开始打印6年免检
        /// </summary>
        public static byte[] PRINT_LNMJ_START = { 0x24, 0x03, 0x18, 0xe4, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印6年免检-GMC准备就绪
        /// </summary>
        public static byte[] PRINT_LNMJ_GMC_READY = { 0x24, 0x05, 0x18, 0xe2, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印6年免检-送入打印位置
        /// </summary>
        public static byte[] PRINT_LNMJ_PRINTER_READY = { 0x24, 0x01, 0x16, 0xe8, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印6年免检-未送入打印位置
        /// </summary>
        public static byte[] PRINT_LNMJ_PRINTER_ERROR = { 0x24, 0x07, 0x13, 0xe5, 0x4e, 0x0d, 0x0a };

        /// <summary>
        /// 打印6年免检-打印完成
        /// </summary>
        public static byte[] PRINT_LNMJ_PRINT_COMPLETED = { 0x24, 0x06, 0x19, 0xe0, 0x00, 0x0d, 0x0a };


        /// <summary>
        /// 打印6年免检-富士通打印失败
        /// </summary>
        public static byte[] PRINT_LNMJ_PRINT_FAILED = { 0x24, 0x06, 0x1a, 0xdf, 0x00, 0x0d, 0x0a };


        /// <summary>
        /// 打印6年免检-完成
        /// </summary>
        public static byte[] PRINT_LNMJ_ALL_COMPLETED = { 0x24, 0x07, 0x18, 0xe0, 0x00, 0x0d, 0x0a };




        public static byte[] CAMERA_SELF_CHECKING_START = { 0x24, 0x12, 0x18, 0xd5, 0x00, 0x0d, 0x0a };

        public static byte[] CAMERA_SELF_CHECKING_COMPLETE = { 0x24, 0x13, 0x18, 0xd4, 0x00, 0x0d, 0x0a };



        /// <summary>
        /// 打印驾驶证-开始
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_START = { 0x24, 0x04, 0x18, 0xe3, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-GMC准备就绪
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_GMC_READY = { 0x24, 0x05, 0x18, 0xe2, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-取料完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_MATERIAL_READY = { 0x24, 0x01, 0x14, 0xea, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-准备接收条形码
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_BARCODE_PREPARE = { 0x24, 0x0c, 0x18, 0xdb, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-接收条形码正确
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_BARCODE_RIGHT = { 0x24, 0x07, 0x19, 0xdf, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-扫描条形码完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_BARCODE_COMPLETED = { 0x24, 0x03, 0x14, 0xe8, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-EPSON开始打印
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_EPSON_START = { 0x24, 0x02, 0x16, 0xe7, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-EPSON打印完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_EPSON_PRINT_COMPLETED = { 0x24, 0x05, 0x19, 0xe1, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-EPSON进度完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_EPSON_PROCESS_COMPLETED = { 0x24, 0x04, 0x14, 0xe7, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通开始打印
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_START = { 0x24, 0x01, 0x16, 0xe8, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通打印完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_PRINT_COMPLETED = { 0x24, 0x06, 0x19, 0xe0, 0x00, 0x0d, 0x0a };


        /// <summary>
        /// 打印驾驶证-富士通打印失败
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_PRINT_FAILED = { 0x24, 0x06, 0x1a, 0xdf, 0x00, 0x0d, 0x0a };


        /// <summary>
        /// 打印驾驶证-富士通正面完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_FRONT_COMPLETED = { 0x24, 0x05, 0x14, 0xe6, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通是否打印反面
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK_OR_NOT = { 0x24, 0x10, 0x18, 0xd7, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通打印反面
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK = { 0x24, 0x06, 0x18, 0xe1, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通不打印反面
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_NOT_PRINT_BACK = { 0x24, 0x11, 0x18, 0xd6, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-富士通反面完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED = { 0x24, 0x06, 0x14, 0xe5, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-切割完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_CUT_COMPLETED = { 0x24, 0x07, 0x14, 0xe4, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-覆膜完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_PACKAGE_COMPLETED = { 0x24, 0x08, 0x14, 0xe3, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-制证完成
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_ALL_COMPLETED = { 0x24, 0x07, 0x18, 0xe0, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-出料
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_PUSH_OFF = { 0x24, 0x0e, 0x18, 0xd9, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 打印驾驶证-出料仓关闭
        /// </summary>
        public static byte[] PRINT_DRIVING_LICENSE_PUSH_OFF_CLOSE = { 0x24, 0x0f, 0x18, 0xd8, 0x00, 0x0d, 0x0a };







        /// <summary>
        /// 开始单片机自检
        /// </summary>
        public static byte[] START_SCM_SELF_CHECKING = { 0x24, 0x01, 0x18, 0xE6, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 通过单片机自检
        /// </summary>
        public static byte[] SCM_SELF_CHECKING_SUCCESSED = { 0x24, 0x08, 0x18, 0xDF, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 开始GMC自检
        /// </summary>
        public static byte[] START_GMC_SELF_CHECKING = { 0x24, 0x02, 0x18, 0xE5, 0x00, 0x0d, 0x0a };

        /// <summary>
        /// 通过GMC自检
        /// </summary>
        public static byte[] GMC_SELF_CHECKING_SUCCESSED = { 0x24, 0x09, 0x18, 0xDE, 0x00, 0x0d, 0x0a };




        /// <summary>
        /// 开始
        /// </summary>
        public static byte[] START_CAR_LICENCE = { };

        public static bool equals(byte[] a, byte[] b)
        {
            if (a.Length == b.Length)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] != b[i])
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        public static bool equals(byte[] a, params byte[][] byteArrays)
        {
            bool result = false;

            foreach (var b in byteArrays)
            {
                result |= equals(a, b);
            }
            return result;
        }

    }

    public enum ScmStep
    {

        FREE,
        START_COMMUNICATION_CHECKING,
        SELF_CHECK_COMMUNICATION_CHECKING_SUCCESSED,
        SELF_CHECK_COMMUNICATION_CHECKING_FAILED,
        START_SCM_SELF_CHECKING,
        SCM_SELF_CHECKING_SUCCESSED,
        SCM_SELF_CHECKING_FAILD,
        START_GMC_SELF_CHECKING,
        GMC_SELF_CHECKING_SUCCESSED,
        GMC_SELF_CHECKING_FAILD,
        PRINT_LNMJ_START,
        PRINT_LNMJ_COMMUNICATION_CHECKING_SUCCESSED,
        PRINT_LNMJ_COMMUNICATION_CHECKING_FAILED,
        PRINT_LNMJ_PRINTER_READY,
        PRINT_LNMJ_PRINT_COMPLETED,
        PRINT_LNMJ_ALL_COMPLETED,


        PRINT_DRIVING_LICENSE_START,
        PRINT_DRIVING_LICENSE_BARCODE_RIGHT,
        PRINT_DRIVING_LICENSE_BARCODE_READY,
        PRINT_DRIVING_LICENSE_BARCODE_COMPLETED,
        PRINT_DRIVING_LICENSE_WAIT_EPSON,
        PRINT_DRIVING_LICENSE_EPSON_READY,
        PRINT_DRIVING_LICENSE_EPSON_PRINT_COMPLETED,
        PRINT_DRIVING_LICENSE_FUJITSU_FRONT_READY,
        PRINT_DRIVING_LICENSE_FUJITSU_FRONT_COMPLETED,
        PRINT_DRIVING_LICENSE_FUJITSU_BACK_START,
        PRINT_DRIVING_LICENSE_FUJITSU_BACK_READY,
        PRINT_DRIVING_LICENSE_FUJITSU_BACK_COMPLETED,
        PRINT_DRIVING_LICENSE_FUJITSU_PRINT_BACK_OR_NOT,
        PRINT_DRIVING_LICENSE_FUJITSU_ALL_COMPLETED,
        PRINT_DRIVING_LICENSE_WAIT_CUT,
        PRINT_DRIVING_LICENSE_WAIT_PACKAGE,
        PRINT_DRIVING_LICENSE_WAIT_ALL_COMPLETED,
        PRINT_DRIVING_LICENSE_ALL_COMPLETED,



        SCM_ERROR
    }

    public enum ScmStatus
    {
        FREE,
        CHECKING,
        ERROR
    }





}
